BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
373 lines · 26.4 KB · download this file
package BlowfishCMS;
# Mail: the Postmark set-up screen at /admin/mail/. It runs in the contact
# service, the only account that can read the Postmark token, so the token
# never passes through the admin or the public site. Settings it keeps
# (the From address and name, the last check) are in the contact folder's
# mail.json, as is the address messages go to.
use v5.36;
use utf8;
use JSON::PP qw(encode_json decode_json);
use Digest::SHA qw(sha256_hex);
use Encode qw(decode encode);
use Fcntl qw(:flock :DEFAULT);
use Socket qw(inet_ntoa);
our ($base,$data,$db,$q,$method,$csrf,%instance);
# Read when the code loads (a FastCGI worker's environment changes per request).
# The tests point it at a local stand-in for Postmark.
my $postmark_api=$ENV{BLOWFISH_POSTMARK_API} // 'https://api.postmarkapp.com';
sub postmark_api { return $postmark_api }
# Where the Postmark token is kept: the secrets folder, readable only by the
# contact service.
sub mail_token_file { return $base.$instance{secrets}.'/postmark.token' }
# The saved Postmark token ('' if none).
sub mail_token {
open my $fh,'<',mail_token_file() or return '';
my $t=do {local $/;<$fh>};close $fh;$t//='';$t =~ s/\s+//g;
return $t;
}
# The mail settings file (mail.json in the contact folder): the receiving
# address (to), the alerts address, the From address and name, the last
# check and the count of test messages this hour.
sub mail_config_file { return contact_dir().'/mail.json' }
# The mail settings, with the From address defaulting to the settings file's
# mail_from and the From name to the site's title.
sub mail_config {
my %c;
if (open my $fh,'<',mail_config_file()) {my $raw=do {local $/;<$fh>};close $fh;my $saved=attempt {decode_json($raw)};%c=%$saved if ref $saved eq 'HASH'}
$c{from_address}=$instance{mail_from} unless length($c{from_address}//'');
$c{from_name}=setting('site_title') unless length($c{from_name}//'');
return \%c;
}
# Changes some mail settings. It writes a new file and then renames it over
# the old one, so the file is never half-written (rename is all or nothing).
# 0600: only the contact service can read it.
sub mail_config_save (%changes) {
my $c=mail_config();%$c=(%$c,%changes);
my $file=mail_config_file();
sysopen(my $fh,"$file.tmp",O_WRONLY|O_CREAT|O_TRUNC,0600) or die "Can't save the mail settings.\n";
print {$fh} JSON::PP->new->canonical->encode($c);close $fh or die "Can't save the mail settings.\n";
rename "$file.tmp",$file or die "Can't save the mail settings.\n";
}
# The From header: "Site name" <address>.
sub mail_from_header {
my $c=mail_config();my $name=$c->{from_name};$name =~ s/["\\\r\n<>]//g;
return length $name ? qq{"$name" <$c->{from_address}>} : $c->{from_address};
}
# Whether a text looks like an email address we can send to.
sub mail_address_ok ($a) { return ($a//'') =~ /\A[^\s@<>"(),;:\\]+@[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+\z/i }
# A Postmark API call: returns (HTTP status, decoded reply or {}).
# One call to Postmark's web API, with the token in its header, verifying
# Postmark's certificate. Returns (HTTP status, the decoded JSON reply).
sub postmark ($verb,$path,$token,$body=undef) {
require HTTP::Tiny;
my $r=HTTP::Tiny->new(timeout=>20,verify_SSL=>1)->request($verb,postmark_api().$path,{
headers=>{Accept=>'application/json','X-Postmark-Server-Token'=>$token,($body ? ('Content-Type'=>'application/json') : ())},
($body ? (content=>encode_json($body)) : ())});
my $reply=(attempt {decode_json($r->{content}//'')}) // {};
return ($r->{status},ref $reply eq 'HASH' ? $reply : {});
}
# Sends one email through Postmark, from the site's From address.
sub postmark_send ($token,%m) {
return postmark('POST','/email',$token,{From=>mail_from_header(),MessageStream=>'outbound',%m});
}
# What a Postmark error means, and what to do about it.
# Postmark's error codes in plain words, with what to do about each.
sub postmark_problem ($code,$status=0) {
return 'Postmark couldn’t be reached. Check the server’s network and DNS, then try again.' if !$code && ($status==599 || !$status);
my %why=(
10=>'Postmark refused the server token. Copy it again from Postmark: your server → API Tokens.',
300=>'Postmark rejected the message. Check the From and contact addresses.',
400=>'The From address isn’t one Postmark knows. In Postmark, add it under Sender Signatures, or add and verify its domain.',
401=>'The From address is waiting for confirmation. Click the link Postmark emailed to it, or verify its domain.',
405=>'Postmark has paused sending for this account (often a billing or review issue). Check your Postmark account.',
406=>'The contact address has bounced or been marked as spam before, so Postmark won’t send to it. Reactivate it in Postmark (Suppressions) or use another address.',
412=>'Your Postmark account is still pending approval, so it can only send to addresses on the From address’s own domain. Request approval in Postmark, or use a contact address on that domain for now.',
);
return $why{$code} // "Postmark returned error $code.";
}
# The Return-Path record: pm-bounces.<domain> should point at pm.mtasv.net.
# Checked with the system resolver (CNAMEs resolve to the target's addresses).
# The IPv4 addresses a name resolves to (none when it doesn't resolve).
# The IPv4 addresses a host name resolves to (none when it doesn't).
sub host_addresses ($name) {
my (undef,undef,undef,undef,@packed)=gethostbyname($name);
return map {inet_ntoa($_)} grep {defined && length==4} @packed;
}
# Whether pm-bounces.DOMAIN points to Postmark ("ok", "missing", "wrong",
# or "unknown" when Postmark's own name doesn't resolve), by comparing the
# addresses both names resolve to.
sub mail_return_path ($domain) {
my @want=host_addresses('pm.mtasv.net');
return 'unknown' unless @want;
my @have=host_addresses("pm-bounces.$domain");
return 'missing' unless @have;
my %w=map {$_=>1} @want;
return (grep {!$w{$_}} @have) ? 'wrong' : 'ok';
}
# The last N lines of the contact log, for the screen.
sub mail_log_tail ($n) {
open my $fh,'<',contact_dir().'/contact.log' or return ();
my @lines=<$fh>;close $fh;chomp @lines;
return grep {length} @lines[($#lines-$n+1 < 0 ? 0 : $#lines-$n+1)..$#lines];
}
# The Mail screen's own key for signing its forms (it runs in the contact
# service, which can't read the admin's key), made the first time.
sub mail_secret {
my $file=contact_dir().'/csrf.key';
if (!-e $file && sysopen(my $out,$file,O_WRONLY|O_CREAT|O_EXCL,0600)) {print {$out} random_id().random_id();close $out}
open my $fh,'<',$file or die "Mail key unavailable\n";local $/;my $s=<$fh>;close $fh;$s =~ s/\s+//g;
die "Mail key unavailable\n" unless length $s;
return $s;
}
# Checks the token and the sending set-up; the outcome is kept for the status panel.
# Checks the token with Postmark and the Return-Path record, and saves the
# outcome for the status panel.
sub mail_check ($token=mail_token()) {
my %r=(checked_at=>now());
if (length $token) {
my ($status,$reply)=postmark('GET','/server',$token);
if ($status==200) {$r{server}=$reply->{Name}//'(unnamed)';$r{token}='ok'}
else {$r{token}='bad';$r{problem}=postmark_problem($reply->{ErrorCode}//0,$status)}
} else {$r{token}='missing'}
my ($domain)=mail_config()->{from_address} =~ /@(.+)\z/;
$r{return_path}=$domain ? mail_return_path(lc $domain) : 'unknown';
mail_config_save(last_check=>\%r);
return \%r;
}
# Allows at most ten test messages an hour.
sub mail_test_allowed {
# At most ten test messages an hour.
my $c=mail_config();my $hour=int(time/3600);
my $t=($c->{tests}{hour}//0)==$hour ? $c->{tests}{count}//0 : 0;
die "That’s ten test messages this hour. Try again later.\n" if $t>=10;
mail_config_save(tests=>{hour=>$hour,count=>$t+1});
}
# The Mail screen (/admin/mail/), served by the contact service. Owners only.
# It has its own CSRF cookie (bf_mail_csrf). Actions:
# token_save check a pasted token with Postmark, then store it (0400)
# token_remove delete the token
# receiving_save where contact messages go
# alerts_save where update alerts go (empty = none)
# sender_save the From address and name
# check check the set-up again
# test_send send a test message to the receiving address
# Then the screen: the status table, the token and sender forms, the set-up
# steps (open until a token is saved), the addresses, and recent deliveries.
sub mail_admin {
$db //= attempt {database()};
require_admin(0,1) or return;
unless (-d contact_dir() && -w contact_dir()) {
# Reached through the admin service: httpd doesn't send /admin/mail/ to the contact service yet.
admin_page('Mail',section=>'mail',status=>503);
window('mail','<p>The mail settings run in the contact service, and this server doesn’t send <code>/admin/mail/</code> to it yet. On a BlowfishCMS install, run <code>doas blowfishctl httpd</code> once to rewrite the web server configuration.</p>');
end_page();return;
}
attempt {csrf_setup(mail_secret(),'bf_mail_csrf','/admin/mail/');1} or do {header(403,'text/plain; charset=UTF-8');print h(clean_error($@));return};
my $message=param('notice',2000);
if ($method eq 'POST') {
attempt {
my $action=param('action',30);
if ($action eq 'token_save') {
my $token=param('token',200);$token =~ s/\s+//g;
die "Paste the server token from Postmark.\n" unless length $token;
die "That doesn’t look like a Postmark server token (letters, numbers and dashes).\n" unless $token =~ /\A[A-Za-z0-9-]{20,100}\z/;
my ($status,$reply)=postmark('GET','/server',$token);
die postmark_problem($reply->{ErrorCode}//0,$status)."\n" unless $status==200;
my $file=mail_token_file();
sysopen(my $fh,"$file.tmp",O_WRONLY|O_CREAT|O_TRUNC,0400) or die "Can’t save the token: the secrets folder isn’t writable by the contact service.\n";
print {$fh} "$token\n";close $fh or die "Can’t save the token.\n";
rename "$file.tmp",$file or do {unlink "$file.tmp";die "Can’t save the token.\n"};
mail_check($token);
redirect('/admin/mail/?notice='.CGI::escape(encode('UTF-8','Token saved. Postmark server: '.($reply->{Name}//'(unnamed)').'.')));
}
if ($action eq 'token_remove') {
unlink mail_token_file();mail_config_save(last_check=>undef);
redirect('/admin/mail/?notice='.CGI::escape('Token removed. The contact form stops sending until a new one is saved.'));
}
if ($action eq 'receiving_save') {
my $to=lc param('to',254);
die "Receiving address: enter an address such as you\@example.org.\n" unless mail_address_ok($to);
mail_config_save(to=>$to);
redirect('/admin/mail/?notice='.CGI::escape(encode('UTF-8',"Saved. Contact messages go to $to.")));
}
if ($action eq 'alerts_save') {
my $to=lc param('alerts',254);
die "Alerts address: enter an address such as you\@example.org, or leave it empty for no alerts.\n" if length $to && !mail_address_ok($to);
mail_config_save(alerts=>$to);
redirect('/admin/mail/?notice='.CGI::escape(encode('UTF-8',length $to ? "Saved. Update alerts go to $to." : 'Saved. No update alerts are emailed.')).'#alerts');
}
if ($action eq 'sender_save') {
my ($addr,$name)=(lc param('from_address',254),param('from_name',80));
die "From address: enter an address such as site\@example.org.\n" unless mail_address_ok($addr);
die "From name: no quotes, angle brackets or line breaks.\n" if $name =~ /["<>\r\n\\]/;
mail_config_save(from_address=>$addr,from_name=>$name);
mail_check();
redirect('/admin/mail/?notice=Sender%20saved.');
}
if ($action eq 'check') {
my $r=mail_check();
redirect('/admin/mail/?notice='.CGI::escape(encode('UTF-8',$r->{token} eq 'ok' ? 'Checked. Postmark accepts the token.' : $r->{token} eq 'missing' ? 'Checked. No token is saved yet.' : $r->{problem})));
}
if ($action eq 'test_send') {
my $token=mail_token();die "Save a Postmark server token first.\n" unless length $token;
my $to=mail_config()->{to};die "Set the receiving address first (below).\n" unless mail_address_ok($to);
mail_test_allowed();
my ($status,$reply)=postmark_send($token,To=>$to,Subject=>"[$instance{domain}] Test message",
TextBody=>"This is a test message from the Mail screen of $instance{domain}.\n\nIf you're reading this, the contact form can deliver messages to you.\n");
if ($status==200 && defined $reply->{ErrorCode} && $reply->{ErrorCode}==0) {
contact_log('Test message accepted '.($reply->{MessageID}//''));
redirect('/admin/mail/?notice='.CGI::escape(encode('UTF-8',"Postmark accepted the test message for $to. It should arrive within a minute; check spam if it doesn’t.")));
}
contact_log('Test message failed; HTTP='.$status.' errorCode='.($reply->{ErrorCode}//-1));
die postmark_problem($reply->{ErrorCode}//0,$status)."\n";
}
die "Choose an action.\n";
} or $message=failed_action($@);
}
my $c=mail_config();my $token=length mail_token();my $last=$c->{last_check} // {};
my $to=$c->{to};
my ($domain)=$c->{from_address} =~ /@(.+)\z/;$domain=lc($domain//$instance{domain});
admin_page('Mail',section=>'mail',notice=>$message,
intro=>'The contact form sends messages through <a href="https://postmarkapp.com/" target="_blank" rel="noopener">Postmark</a>. Set it up here, then send yourself a test.');
my @rows=(
['Server token',$token ? (($last->{token}//'') eq 'bad' ? ['bad','saved, but Postmark refused it'] : ['ok','saved'.(length($last->{server}//'') ? ' (Postmark server: '.$last->{server}.')' : '')]) : ['bad','not set']],
['From address',['ok',mail_from_header()]],
['Messages go to',mail_address_ok($to) ? ['ok',$to] : ['bad','not set: add the receiving address below']],
['Return-Path DNS record',{ok=>['ok',"pm-bounces.$domain points to Postmark"],missing=>['warn',"pm-bounces.$domain not found (optional, but helps delivery)"],wrong=>['warn',"pm-bounces.$domain points somewhere else"],unknown=>['warn','not checked yet']}->{$last->{return_path}//'unknown'}],
);
my $s='<table class="seo-table mail-status"><tbody>'.join('',map {'<tr><th>'.h($_->[0]).'</th><td class="'.($_->[1][0] eq 'ok' ? 'is-ok' : 'is-warn').'">'.h($_->[1][1]).'</td></tr>'} @rows).'</tbody></table>';
$s.='<p class="media-label">'.(length($last->{checked_at}//'') ? 'Last checked '.h($last->{checked_at}).'.' : 'Not checked yet.').' '.h($last->{problem}//'').'</p>';
$s.='<div class="mail-actions"><form method="post" action="/admin/mail/">'.fields('check','mail').'<button class="buttonlike" type="submit">check again</button></form></div>';
my $test='<form method="post" action="/admin/mail/" class="mail-actions mail-test">'.fields('test_send','mail').'<button class="buttonlike is-primary" type="submit"'.($token && mail_address_ok($to) ? '' : ' disabled').'>send a test message</button>'
.'<span class="optional">'.($token && mail_address_ok($to) ? 'Sends a message to the receiving address through Postmark.' : 'Needs the Postmark token and the receiving address first.').'</span></form>';
my @log=reverse mail_log_tail(8);
my $deliveries=(@log ? '<ul class="mail-log">'.join('',map {'<li><code>'.h($_).'</code></li>'} @log).'</ul>' : '<p class="empty-media">Nothing sent yet.</p>');
my $t='<form method="post" action="/admin/mail/" class="admin-form">'.fields('token_save','mail')
.'<label>Server token<input name="token" type="password" autocomplete="off" spellcheck="false" maxlength="200" required placeholder="'.($token ? 'saved; paste a new one to replace it' : 'paste the token').'"><span class="optional">In Postmark: open your server → API Tokens → copy the Server API token. It’s checked with Postmark before it’s saved, and it’s never shown again.</span></label>'
.'<button class="buttonlike" type="submit">save</button></form>';
$t.='<form method="post" action="/admin/mail/" class="delete-form" data-confirm="Remove the Postmark token? The contact form stops sending until a new one is saved.">'.fields('token_remove','mail').'<button class="text-button danger" type="submit">remove the token</button></form>' if $token;
my $receiving=('<form method="post" action="/admin/mail/" class="admin-form">'.fields('receiving_save','mail')
.'<label>Receiving address<input name="to" type="email" value="'.h($to).'" maxlength="254" required><span class="optional">Where messages from the contact form are delivered. Visitors never see it.</span></label><button class="buttonlike" type="submit">save</button></form>');
my $sender=('<form method="post" action="/admin/mail/" class="admin-form">'.fields('sender_save','mail')
.'<div class="theme-editor__grid"><label>From address<input name="from_address" type="email" value="'.h($c->{from_address}).'" maxlength="254" required><span class="optional">An address on a domain you’ve verified in Postmark, such as site@'.h($domain).'. It doesn’t need its own mailbox; replies go to the visitor.</span></label>'
.'<label>From name<input name="from_name" value="'.h($c->{from_name}).'" maxlength="80"><span class="optional">Shown as the sender in your inbox.</span></label></div><button class="buttonlike" type="submit">save</button></form>');
my $steps=('<ol class="mail-steps">'
.'<li><strong>Create a Postmark account</strong> at postmarkapp.com and a <em>server</em> for this site (the free plan covers a contact form).</li>'
.'<li><strong>Verify your domain</strong>: Postmark → Sender Signatures → Add Domain → <code>'.h($domain).'</code>. Postmark shows two DNS records; add both where your domain’s DNS is managed:'
.'<ul><li>DKIM: a <code>TXT</code> record named like <code>2026…pm._domainkey.'.h($domain).'</code>. Copy its name and value exactly from Postmark.</li>'
.'<li>Return-Path: a <code>CNAME</code> record <code>pm-bounces.'.h($domain).'</code> → <code>pm.mtasv.net</code></li></ul>'
.'Then press <em>Verify</em> in Postmark. DNS changes can take up to an hour.</li>'
.'<li><strong>Paste the server token</strong> above (Postmark → your server → API Tokens).</li>'
.'<li><strong>Set the From address</strong> to an address on that domain, and the receiving address under <em>messages</em>.</li>'
.'<li><strong>Send a test message.</strong> New Postmark accounts can only send to their own domain until Postmark approves them; request approval from your Postmark account page.</li>'
.'<li>Optional, for better delivery: a DMARC record, a <code>TXT</code> record at <code>_dmarc.'.h($domain).'</code> with the value <code>v=DMARC1; p=none;</code></li>'
.'</ol>');
# Postmark (its status, token, sender and how to set it up), then the messages, then what was sent.
window('postmark',$s.'<div class="box-part"><h3>Token</h3>'.$t.'</div><div class="box-part"><h3>Sender</h3>'.$sender.'</div>'
.'<details class="box-part mail-setup"'.($token ? '' : ' open').'><summary>Setting up Postmark</summary>'.$steps.'</details>');
my $alerts='<form method="post" action="/admin/mail/" class="admin-form box-part" id="alerts">'.fields('alerts_save','mail')
.'<label>Update alerts <input name="alerts" type="email" value="'.h($c->{alerts}//'').'" maxlength="254"><span class="optional">Optional. When BlowfishCMS, an add-on or a theme has an update, the server’s nightly check emails this address once. Leave it empty for none.</span></label><button class="buttonlike" type="submit">save</button></form>';
window('messages',$receiving.$test.$alerts);
window('recent deliveries',$deliveries);
end_page();
}
# ---- Mail from add-ons ------------------------------------------------------------
# Only the contact form's account can read the Postmark token and the Mail
# settings, so other services queue their messages: mail_queue writes one as
# a file in the calling service's own outbox; every minute blowfishctl moves
# outbox files into the contact folder's mailq/, and runs --mail-send as the
# contact form's account, which sends them. A message to "owner" goes to the
# update alerts address, or else to where contact messages go.
# mail_queue('store', to=>'owner'|address, subject=>…, text=>…, html=>…,
# reply_to=>'owner'|address, from_name=>…, tag=>…, headers=>{Name=>Value},
# stream=>'outbound'|'broadcast')
# The outbox folder for a part of the site: an add-on's own data folder's
# outbox/, else the admin's. Refuses a symbolic link, so a message file
# can't be written somewhere else.
sub mail_outbox ($source) {
my @dirs=(($source ne 'core' ? addon_data_dir($source).'/outbox' : ()),$base.$instance{data}.'/outbox');
for my $dir (@dirs) {
my $parent=$dir =~ s{/outbox\z}{}r;
next unless -d $parent && -w $parent;
mkdir $dir,0700 unless -d $dir;
return $dir if -d $dir && -w $dir && !-l $dir;
}
die "This part of the site can’t send mail.\n";
}
# Queues an email (add-ons call this): checks it, writes it as JSON to the
# outbox under a temporary name and renames it into place once complete, so
# the relay never picks up half a message. Returns its name.
sub mail_queue ($source,%m) {
die "A message needs someone to send it to.\n" unless ($m{to}//'') eq 'owner' || mail_address_ok($m{to});
die "A message needs a subject.\n" unless length($m{subject}//'');
die "A message needs a text.\n" unless length($m{text}//'');
die "That reply address isn’t an email address.\n" if length($m{reply_to}//'') && $m{reply_to} ne 'owner' && !mail_address_ok($m{reply_to});
my %msg=(source=>$source,queued=>now(),map {($_=>$m{$_})} grep {defined $m{$_}} qw(to subject text html reply_to from_name tag headers stream));
my $json=JSON::PP->new->utf8->canonical->encode(\%msg);
die "That message is too long to send.\n" if length($json)>1_000_000;
my $dir=mail_outbox($source);
my $name=time().'-'.substr(random_id(),0,16);
sysopen(my $fh,"$dir/.$name.tmp",O_WRONLY|O_CREAT|O_EXCL,0600) or die "The message couldn’t be queued.\n";
print {$fh} $json;close $fh or die "The message couldn’t be queued.\n";
rename "$dir/.$name.tmp","$dir/$name.json" or die "The message couldn’t be queued.\n";
return $name;
}
# Run as the contact form's account: sends what's in mailq/. Exit 0 when the
# queue was worked through, 3 when there's no token yet (the messages wait).
# site.pl --mail-send, run every minute as the contact service's account:
# sends up to 300 queued messages from mailq/, oldest first. "owner" means
# the alerts address, else the receiving address. A message Postmark refuses
# for good (a bad or suppressed address) is dropped; any other failure is
# counted and tried again next minute, up to 20 times, then moved to
# mailq/failed/. If Postmark is down or refuses the token, the rest wait for
# the next run. Header names an add-on asks for are filtered, so it can't set
# To, From and the like itself.
sub mail_send_cli {
my $q=contact_dir().'/mailq';
my @files=sort grep {/\/[A-Za-z0-9._-]+\.json\z/ && -f && !-l} glob("$q/*.json");
return 0 unless @files;
my $token=mail_token();
unless (length $token) {say 'No Postmark token is saved; '.scalar(@files).' messages wait.';return 3}
my $c=mail_config();
my $owner=mail_address_ok($c->{alerts}) ? $c->{alerts} : mail_address_ok($c->{to}) ? $c->{to} : '';
my ($sent,$kept)=(0,0);
for my $file (@files[0..($#files<299 ? $#files : 299)]) {
my $m=attempt {open my $fh,'<:raw',$file or die;local $/;JSON::PP->new->utf8->decode(<$fh>)};
my $drop=sub ($why) {contact_log("Queued message dropped ($why): ".($file =~ s{.*/}{}r));unlink $file};
unless (ref $m eq 'HASH') {$drop->('unreadable');next}
my $to=($m->{to}//'') eq 'owner' ? $owner : $m->{to}//'';
unless (mail_address_ok($to)) {
# To the owner with no address set: it waits until one is.
if (($m->{to}//'') eq 'owner') {$kept++;next}
$drop->('no valid recipient');next;
}
my $from=mail_from_header();
if (length($m->{from_name}//'')) {my $n=$m->{from_name} =~ s/["\\\r\n<>]//gr;$from=qq{"$n" <$c->{from_address}>} if length $n}
my %body=(From=>$from,To=>$to,Subject=>substr($m->{subject}//'',0,300),TextBody=>$m->{text}//'',
(length($m->{html}//'') ? (HtmlBody=>$m->{html}) : ()),(do {my $r=($m->{reply_to}//'') eq 'owner' ? $owner : $m->{reply_to};mail_address_ok($r) ? (ReplyTo=>$r) : ()}),
(length($m->{tag}//'') ? (Tag=>substr($m->{tag},0,50)) : ()),
(ref $m->{headers} eq 'HASH' ? (Headers=>[map {{Name=>$_,Value=>$m->{headers}{$_}}} grep {/\A[A-Za-z][A-Za-z0-9-]{0,40}\z/ && !/\A(?:from|to|cc|bcc|subject|reply-to|sender)\z/i} sort keys %{$m->{headers}}]) : ()),
MessageStream=>(($m->{stream}//'') eq 'broadcast' ? 'broadcast' : 'outbound'));
my ($status,$reply)=postmark('POST','/email',$token,\%body);
my $code=$reply->{ErrorCode}//-1;
if ($status==200 && $code==0) {contact_log('Queued message from '.($m->{source}//'?').' accepted '.($reply->{MessageID}//''));unlink $file;$sent++;next}
# The recipient is refused for good (a bad or inactive address): it isn't tried again.
if ($status==422 && ($code==300 || $code==406)) {$drop->("Postmark error $code");next}
$m->{attempts}=($m->{attempts}//0)+1;
contact_log('Queued message from '.($m->{source}//'?').' failed; HTTP='.$status.' errorCode='.$code.' attempt '.$m->{attempts});
if ($m->{attempts}>=20) {mkdir "$q/failed",0700;rename $file,"$q/failed/".($file =~ s{.*/}{}r);next}
if (open my $out,'>:raw',"$file.tmp") {print {$out} JSON::PP->new->utf8->canonical->encode($m);close $out;rename "$file.tmp",$file}
$kept++;
last if $status==401 || $status==0 || $status>=500; # Postmark or the token: try the rest next time
}
say "Sent $sent; $kept waiting.";
return 0;
}
1;