without SMTP_SERVER send directly to destination
[MQR.git] / scripts / mqr-smtp.pl
1 #!/usr/bin/perl
2
3 use warnings;
4 use strict;
5
6 use AnyEvent::SMTP::Server;
7 use AnyEvent::SMTP::Client qw(sendmail);
8 use Data::Dump qw(dump);
9
10 use lib 'lib';
11 use MQR::Redis;
12
13 my $host = $ENV{SMTP_HOST} || '0.0.0.0';
14 my $port = $ENV{SMTP_PORT} || 2525;
15 my $server = $ENV{SMTP_SERVER};
16
17 MQR::Redis->redis->psubscribe( "SEND $host:$port smtp *", sub {
18         my ( $message, $channel ) = @_;
19         my ( undef, undef, undef, $from, $to ) = split(/\s/,$channel);
20         warn "sendmail $from -> $to | $message\n";
21
22         my $f = $to;
23         $f =~ s/\@.+//;
24         $f .= '@mqr.rot13.org';
25
26         sendmail
27                 from => $f,
28                 to => $from,
29                 data => "Subject: $message\n\n$message",
30                 cb => sub {
31                         my ($ok,$error) = @_;
32                         warn "# sendmail ", $ok && "OK $ok" || "ERROR: $error", "\n";
33                 },
34 #               debug => 1, # XXX
35                 server => $server,
36 });
37
38 my $smtp = AnyEvent::SMTP::Server->new( host => $host, port => $port );
39
40 $smtp->reg_cb(
41         client => sub {
42                 my ($s,$con) = @_;
43                 warn "Client from $con->{host}:$con->{port} connected\n";
44         },
45         disconnect => sub {
46                 my ($s,$con) = @_;
47                 warn "Client from $con->{host}:$con->{port} gone\n";
48         },
49         mail => sub {
50                 my ($s,$mail) = @_;
51                 my $from = $mail->{from};
52                 warn "Received mail from $from to ",join(' and ',@{$mail->{to}}), "\n$mail->{data}\n";
53                 foreach my $to ( @{ $mail->{to} } ) {
54                         my $subject = $1 if $mail->{data} =~ m/^Subject:\s*(.+)$/m;
55                         $subject =~ s/[\s\r\n]+$//; # XXX important!
56                         MQR::Redis->publish( "MSG $host:$port smtp $from $to" => $subject );
57                 }
58         },
59 );
60
61 $smtp->start;
62 AnyEvent->condvar->recv;