forked from olegwtf/p5-Mojo-SMTP-Client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Client.pm
1055 lines (847 loc) · 30.6 KB
/
Client.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package Mojo::SMTP::Client;
use Mojo::Base 'Mojo::EventEmitter';
use Mojo::IOLoop;
use Mojo::IOLoop::Client;
use Mojo::IOLoop::Delay;
use Mojo::IOLoop::Stream;
use Mojo::Util 'b64_encode';
use Mojo::SMTP::Client::Response;
use Mojo::SMTP::Client::Exception;
use Scalar::Util 'weaken';
use Carp;
our $VERSION = '0.12';
use constant {
CMD_OK => 2,
CMD_MORE => 3,
CMD_CONNECT => 1,
CMD_EHLO => 2,
CMD_HELO => 3,
CMD_STARTTLS => 10,
CMD_AUTH => 11,
CMD_FROM => 4,
CMD_TO => 5,
CMD_DATA => 6,
CMD_DATA_END => 7,
CMD_RESET => 8,
CMD_QUIT => 9,
};
our %CMD = (
&CMD_CONNECT => 'CMD_CONNECT',
&CMD_EHLO => 'CMD_EHLO',
&CMD_HELO => 'CMD_HELO',
&CMD_STARTTLS => 'CMD_STARTTLS',
&CMD_AUTH => 'CMD_AUTH',
&CMD_FROM => 'CMD_FROM',
&CMD_TO => 'CMD_TO',
&CMD_DATA => 'CMD_DATA',
&CMD_DATA_END => 'CMD_DATA_END',
&CMD_RESET => 'CMD_RESET',
&CMD_QUIT => 'CMD_QUIT',
);
has address => 'localhost';
has port => sub { $_[0]->tls ? 465 : 25 };
has tls => 0;
has 'tls_ca';
has 'tls_cert';
has 'tls_key';
has hello => 'localhost.localdomain';
has connect_timeout => sub { $ENV{MOJO_CONNECT_TIMEOUT} || 10 };
has inactivity_timeout => sub { $ENV{MOJO_INACTIVITY_TIMEOUT} // 20 };
has ioloop => sub { Mojo::IOLoop->new };
has autodie => 0;
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_);
weaken(my $this = $self);
$self->{resp_checker} = sub {
my ($delay, $resp) = @_;
$this->emit(response => $this->{last_cmd}, $resp);
unless (substr($resp->code, 0, 1) == $this->{expected_code}) {
die $resp->error(Mojo::SMTP::Client::Exception::Response->new($resp->message)->code($resp->code));
}
$delay->pass($resp);
};
$self;
}
sub send {
my $self = shift;
my $cb = @_ % 2 == 0 ? undef : pop;
my @steps;
$self->{nb} = $cb ? 1 : 0;
delete $self->{new_cmd};
# user changed SMTP server or server sent smth while it shouldn't
if ($self->{stream} && (($self->{server} ne $self->_server) ||
($self->{stream}->is_readable && !$self->{starttls} && !$self->{authorized} &&
grep {$self->{last_cmd} == $_} (CMD_CONNECT, CMD_DATA_END, CMD_RESET)))
) {
$self->_rm_stream();
}
unless ($self->{stream}) {
push @steps, sub {
my $delay = shift;
# connect
$self->{starttls} = $self->{authorized} = 0;
$self->emit('start');
$self->{server} = $self->_server;
$self->{last_cmd} = CMD_CONNECT;
my $connect_cb = $delay->begin;
$self->{client} = Mojo::IOLoop::Client->new(reactor => $self->_ioloop->reactor);
$self->{client}->on(connect => $connect_cb);
$self->{client}->on(error => $connect_cb);
$self->{client}->connect(
address => $self->address,
port => $self->port,
timeout => $self->connect_timeout,
tls => $self->tls,
tls_ca => $self->tls_ca,
tls_cert => $self->tls_cert,
tls_key => $self->tls_key
);
},
sub {
# read response
my $delay = shift;
delete $self->{client};
# check is this a handle
Mojo::SMTP::Client::Exception::Stream->throw($_[0]) unless eval { *{$_[0]} };
$self->_make_stream($_[0], $self->_ioloop);
$self->_read_response($delay->begin, 0);
$self->{expected_code} = CMD_OK;
},
# check response
$self->{resp_checker};
if (!@_ || $_[0] ne 'hello') {
unshift @_, hello => $self->hello;
}
}
else {
$self->{stream}->start;
}
push @steps, $self->_make_cmd_steps(0, @_);
# non-blocking
my $delay = $self->{delay} = Mojo::IOLoop::Delay
->new(ioloop => $self->_ioloop)
->steps(@steps)
->catch(sub {
# handle exceptions which were thrown
my ($ioloop, $err) = @_;
unless ($err->isa("Mojo::SMTP::Client::Exception") or $err->isa("Mojo::SMTP::Client::Response")) {
$err = Mojo::SMTP::Client::Response->new('', error => $err)
}
$ioloop->emit(finish => $err);
});
$delay->on(finish => sub {
if ($cb) {
my $r = $_[1];
# handle exceptions which where returned
if ($r->isa('Mojo::SMTP::Client::Exception')) {
$r = Mojo::SMTP::Client::Response->new('', error => $r);
}
$cb->($self, $r);
$cb = undef;
delete $self->{delay};
}
});
# blocking
my $resp;
unless ($self->{nb}) {
$cb = sub {
$resp = pop;
};
$delay->wait;
return $self->autodie && $resp->error ? die $resp->error : $resp;
}
}
sub prepend_cmd {
my $self = shift;
croak "no active `send' calls" unless exists $self->{delay};
my $remaining = $self->{delay}->remaining;
my $i;
for ($i=0; $i<@$remaining; $i++) {
if (exists $self->{new_cmd}{$remaining->[$i]}) {
last;
}
}
croak "no commands in the queue, can't prepend to nothing" if $i == @$remaining;
splice @$remaining, $i, 0, $self->_make_cmd_steps(1, @_);
}
sub _ioloop {
my ($self) = @_;
return $self->{nb} ? Mojo::IOLoop->singleton : $self->ioloop;
}
sub _server {
my $self = shift;
return $self->address.':'.$self->port.':'.$self->tls;
}
sub _make_stream {
my ($self, $sock, $loop) = @_;
weaken $self;
my $error_handler = sub {
delete($self->{cleanup_cb})->() if $self->{cleanup_cb};
$self->{delay}->remaining([]); # remove remaining steps
$self->_rm_stream();
$self->{delay}->emit(finish => $_[0]);
};
$self->{stream} = Mojo::IOLoop::Stream->new($sock);
$self->{stream}->reactor($loop->reactor);
$self->{stream}->start;
$self->{stream}->on(timeout => sub {
$error_handler->(Mojo::SMTP::Client::Exception::Stream->new('Inactivity timeout'));
});
$self->{stream}->on(error => sub {
$error_handler->(Mojo::SMTP::Client::Exception::Stream->new($_[-1]));
});
$self->{stream}->on(close => sub {
$error_handler->(Mojo::SMTP::Client::Exception::Stream->new('Socket closed unexpectedly by remote side'));
});
}
sub _make_cmd_steps {
my ($self, $prepend, @cmd) = @_;
weaken $self;
my @steps;
for (my $i=0; $i<@cmd; $i+=2) {
my $mi = $i+1;
if ($cmd[$i] eq 'hello') { # EHLO/HELO
push @steps, $self->_new_cmd(sub {
my $delay = shift;
$self->_write_cmd('EHLO ' . $cmd[$mi], CMD_EHLO);
$self->_read_response($delay->begin, !$prepend && $mi == $#cmd);
$self->{expected_code} = CMD_OK;
}),
sub {
eval { $self->{resp_checker}->(@_); $_[1]->{checked} = 1 };
if (my $e = $@) {
die $e unless ($e->can('error') and $e->error->isa('Mojo::SMTP::Client::Exception::Response'));
my $delay = shift;
$self->{stream}->start if !$prepend && $mi == $#cmd; # XXX: _read_response may stop stream
$self->_write_cmd('HELO ' . $cmd[$mi], CMD_HELO);
$self->_read_response($delay->begin, !$prepend && $mi == $#cmd);
}
},
sub {
my ($delay, $resp) = @_;
return $delay->pass($resp) if delete $resp->{checked};
$self->{resp_checker}->($delay, $resp);
}
}
elsif ($cmd[$i] eq 'starttls') { # STARTTLS
require IO::Socket::SSL and IO::Socket::SSL->VERSION(0.98);
push @steps, $self->_new_cmd(sub {
my $delay = shift;
$self->_write_cmd('STARTTLS', CMD_STARTTLS);
$self->_read_response($delay->begin, !$prepend && $mi == $#cmd);
$self->{expected_code} = CMD_OK;
}),
$self->{resp_checker},
sub {
my $delay = shift;
$self->{stream}->stop;
$self->{stream}->timeout(0);
my ($tls_cb, $tid, $loop, $sock);
my $error_handler = sub {
$loop->remove($tid);
$loop->reactor->remove($sock);
$sock = undef;
$tls_cb->($delay, 0, @_>=2 ? $_[1] : 'Inactivity timeout');
$tls_cb = $delay = undef;
};
$sock = IO::Socket::SSL->start_SSL(
$self->{stream}->steal_handle,
SSL_ca_file => $self->tls_ca,
SSL_cert_file => $self->tls_cert,
SSL_key_file => $self->tls_key,
SSL_verify_mode => $self->tls_ca ? 0x01 : 0x00,
SSL_verifycn_name => $self->address,
SSL_verifycn_scheme => $self->tls_ca ? 'smtp' : undef,
SSL_startHandshake => 0,
SSL_error_trap => $error_handler
)
or return $delay->pass(0, $IO::Socket::SSL::SSL_ERROR);
$tls_cb = $delay->begin;
$loop = $self->_ioloop;
$tid = $loop->timer($self->inactivity_timeout => $error_handler);
$loop->reactor->io($sock => sub {
if ($sock->connect_SSL) {
$loop->remove($tid);
$loop->reactor->remove($sock);
$self->_make_stream($sock, $loop);
$self->{starttls} = 1;
$sock = $loop = undef;
$tls_cb->($delay, 1);
$tls_cb = $delay = undef;
return;
}
return $loop->reactor->watch($sock, 1, 0)
if $IO::Socket::SSL::SSL_ERROR == IO::Socket::SSL::SSL_WANT_READ();
return $loop->reactor->watch($sock, 0, 1)
if $IO::Socket::SSL::SSL_ERROR == IO::Socket::SSL::SSL_WANT_WRITE();
})->watch($sock, 0, 1);
},
sub {
my ($delay, $success, $error) = @_;
unless ($success) {
$self->_rm_stream();
Mojo::SMTP::Client::Exception::Stream->throw($error);
}
$delay->pass;
}
}
elsif ($cmd[$i] eq 'auth') { # AUTH
push @steps, $self->_new_cmd(sub {
my $delay = shift;
$self->_write_cmd('AUTH PLAIN '.b64_encode(join("\0", '', $cmd[$mi]->{login}, $cmd[$mi]->{password}), ''), CMD_AUTH);
$self->_read_response($delay->begin, !$prepend && $mi == $#cmd);
$self->{expected_code} = CMD_OK;
}),
$self->{resp_checker},
sub {
my $delay = shift;
$self->{authorized} = 1;
$delay->pass;
}
}
elsif ($cmd[$i] eq 'from') { # FROM
push @steps, $self->_new_cmd(sub {
my $delay = shift;
$self->_write_cmd('MAIL FROM:<'.$cmd[$mi].'>', CMD_FROM);
$self->_read_response($delay->begin, !$prepend && $mi == $#cmd);
$self->{expected_code} = CMD_OK;
}),
$self->{resp_checker}
}
elsif ($cmd[$i] eq 'to') { # TO
my $cur = 0;
my $count = ref $cmd[$mi] ? @{$cmd[$mi]} : 1;
for my $to (ref $cmd[$mi] ? @{$cmd[$mi]} : $cmd[$mi]) {
my $j = ++$cur;
push @steps, $self->_new_cmd(sub {
my $delay = shift;
$self->_write_cmd('RCPT TO:<'.$to.'>', CMD_TO);
$self->_read_response($delay->begin, !$prepend && $mi == $#cmd && $j == $count);
$self->{expected_code} = CMD_OK;
}),
$self->{resp_checker}
}
}
elsif ($cmd[$i] eq 'data') { # DATA
push @steps, $self->_new_cmd(sub {
my $delay = shift;
$self->_write_cmd('DATA', CMD_DATA);
$self->_read_response($delay->begin, 0);
$self->{expected_code} = CMD_MORE;
}),
$self->{resp_checker};
if (ref $cmd[$mi] eq 'CODE') {
my ($data_writer, $data_writer_cb);
my $was_nl;
my $last_ch;
$data_writer = sub {
my $delay = shift;
unless ($data_writer_cb) {
$data_writer_cb = $delay->begin;
$self->{cleanup_cb} = sub {
undef $data_writer;
};
}
my $data = $cmd[$mi]->();
$data = $$data if ref $data;
unless (length($data) > 0) {
$self->_write_cmd(($was_nl ? '' : Mojo::SMTP::Client::Response::CRLF).'.', CMD_DATA_END);
$self->_read_response($data_writer_cb, !$prepend && $mi == $#cmd);
$self->{expected_code} = CMD_OK;
return delete($self->{cleanup_cb})->();
}
# The following part if heavily inspired by Net::Cmd
my $first_ch = '';
# We have not send anything yet, so last_ch = "\012" means we are at the start of a line (^. -> ..)
$last_ch = "\012" unless defined $last_ch;
if ($last_ch eq "\015") {
# Remove \012 so it does not get prefixed with another \015 below
# and escape the . if there is one following it because the fixup
# below will not find it
$first_ch = "\012" if $data =~ s/^\012(\.?)/$1$1/;
}
elsif ($last_ch eq "\012") {
# Fixup below will not find the . as the first character of the buffer
$first_ch = "." if $data =~ /^\./;
}
$data =~ s/\015?\012(\.?)/\015\012$1$1/g;
substr($data, 0, 0) = $first_ch;
$last_ch = substr($data, -1, 1);
$was_nl = _has_nl($data);
$self->{stream}->write($data, $data_writer);
};
push @steps, $data_writer, $self->{resp_checker};
}
else {
push @steps, sub {
my $delay = shift;
(ref $cmd[$mi] ? ${$cmd[$mi]} : $cmd[$mi]) =~ s/\015?\012(\.?)/\015\012$1$1/g; # turn . into .. if it's first character of the line and normalize newline
$self->{stream}->write(ref $cmd[$mi] ? ${$cmd[$mi]} : $cmd[$mi], $delay->begin);
},
sub {
my $delay = shift;
$self->_write_cmd((_has_nl($cmd[$mi]) ? '' : Mojo::SMTP::Client::Response::CRLF).'.', CMD_DATA_END);
$self->_read_response($delay->begin, !$prepend && $mi == $#cmd);
$self->{expected_code} = CMD_OK;
},
$self->{resp_checker}
}
}
elsif ($cmd[$i] eq 'reset') { # RESET
push @steps, $self->_new_cmd(sub {
my $delay = shift;
$self->_write_cmd('RSET', CMD_RESET);
$self->_read_response($delay->begin, !$prepend && $mi == $#cmd);
$self->{expected_code} = CMD_OK;
}),
$self->{resp_checker}
}
elsif ($cmd[$i] eq 'quit') { # QUIT
push @steps, $self->_new_cmd(sub {
my $delay = shift;
$self->_write_cmd('QUIT', CMD_QUIT);
$self->_read_response($delay->begin, !$prepend && $mi == $#cmd);
$self->{expected_code} = CMD_OK;
}),
$self->{resp_checker}, sub {
my $delay = shift;
$self->_rm_stream();
$delay->pass(@_);
}
}
else {
croak 'unrecognized command: ', $cmd[$i];
}
}
return @steps;
}
sub _new_cmd {
my ($self, $sub) = @_;
$self->{new_cmd}{$sub} = 1;
$sub;
}
sub _write_cmd {
my ($self, $cmd, $cmd_const) = @_;
$self->{last_cmd} = $cmd_const;
$self->{stream}->write($cmd.Mojo::SMTP::Client::Response::CRLF);
}
sub _read_response {
my ($self, $cb, $last) = @_;
$self->{stream}->timeout($self->inactivity_timeout);
my $resp = '';
$self->{stream}->on(read => sub {
$resp .= $_[-1];
if ($resp =~ /^\d+(?:\s[^\n]*)?\n$/m) {
$self->{stream}->unsubscribe('read');
if ($last) {
$self->{stream}->timeout(0);
$self->{stream}->stop;
}
$cb->($self, Mojo::SMTP::Client::Response->new($resp));
}
});
}
sub _rm_stream {
my $self = shift;
$self->{stream}->unsubscribe('close')
->unsubscribe('timeout')
->unsubscribe('error')
->unsubscribe('read');
delete $self->{stream};
}
sub _has_nl {
substr(ref $_[0] ? ${$_[0]} : $_[0], -2, 2) eq Mojo::SMTP::Client::Response::CRLF;
}
sub DESTROY {
my $self = shift;
if ($self->{stream}) {
$self->_rm_stream();
}
}
1;
__END__
=pod
=encoding utf8
=head1 NAME
Mojo::SMTP::Client - non-blocking SMTP client based on Mojo::IOLoop
=head1 SYNOPSIS
=over
# blocking
my $smtp = Mojo::SMTP::Client->new(address => '10.54.17.28', autodie => 1);
$smtp->send(
from => 'me@from.org',
to => 'you@to.org',
data => join("\r\n", 'From: me@from.org',
'To: you@to.org',
'Subject: Hello world!',
'',
'This is my first message!'
),
quit => 1
);
warn "Sent successfully"; # else will throw exception because of `autodie'
=back
=over
# non-blocking
my $smtp = Mojo::SMTP::Client->new(address => '10.54.17.28');
$smtp->send(
from => 'me@from.org',
to => 'you@to.org',
data => join("\r\n", 'From: me@from.org',
'To: you@to.org',
'Subject: Hello world!',
'',
'This is my first message!'
),
quit => 1,
sub {
my ($smtp, $resp) = @_;
warn $resp->error ? 'Failed to send: '.$resp->error : 'Sent successfully';
Mojo::IOLoop->stop;
}
);
Mojo::IOLoop->start;
=back
=head1 DESCRIPTION
With C<Mojo::SMTP::Client> you can easily send emails from your Mojolicious application without
blocking of C<Mojo::IOLoop>.
=head1 EVENTS
C<Mojo::SMTP::Client> inherits all events from L<Mojo::EventEmitter> and can emit the following new ones
=head2 start
$smtp->on(start => sub {
my ($smtp) = @_;
# some servers delays first response to prevent SPAM
$smtp->inactivity_timeout(5*60);
});
Emitted whenever a new connection is about to start.
=head2 response
$smtp->on(response => sub {
my ($smtp, $cmd, $resp) = @_;
if ($cmd == Mojo::SMTP::Client::CMD_CONNECT) {
# and after first response others should be fast enough
$smtp->inactivity_timeout(10);
}
});
Emitted for each SMTP response from the server. C<$cmd> is a command L<constant|/CONSTANTS> for which this
response was sent. C<$resp> is L<Mojo::SMTP::Client::Response> object.
=head1 ATTRIBUTES
C<Mojo::SMTP::Client> implements the following attributes, which you can set in the constructor or get/set later
with object method call
=head2 address
Address of SMTP server (ip or domain name). Default is C<localhost>
=head2 port
Port of SMTP server. Default is C<25> for plain connection and C<465> if TLS is enabled.
=head2 tls
Enable TLS. Should be true if SMTP server expects encrypted connection. Default is false.
Proper version of L<IO::Socket::SSL> should be installed for TLS support in L<Mojo::IOLoop::Client>,
which you can find with C<mojo version> command.
=head2 tls_ca
Path to TLS certificate authority file. Also activates hostname verification.
=head2 tls_cert
Path to the TLS certificate file.
=head2 tls_key
Path to the TLS key file.
=head2 hello
SMTP requires that you identify yourself. This option specifies a string to pass as your mail domain.
Default is C<localhost.localdomain>
=head2 connect_timeout
Maximum amount of time in seconds establishing a connection may take before getting canceled,
defaults to the value of the C<MOJO_CONNECT_TIMEOUT> environment variable or C<10>
=head2 inactivity_timeout
Maximum amount of time in seconds a connection can be inactive before getting closed,
defaults to the value of the C<MOJO_INACTIVITY_TIMEOUT> environment variable or C<20>.
Setting the value to C<0> will allow connections to be inactive indefinitely
=head2 ioloop
Event loop object to use for blocking I/O operations, defaults to a L<Mojo::IOLoop> object
=head2 autodie
Defines should or not C<Mojo::SMTP::Client> throw exceptions for any type of errors. This only usable for
blocking usage of C<Mojo::SMTP::Client>, because non-blocking one should never die. Throwed
exception will be one of the specified in L<Mojo::SMTP::Client::Exception>. When autodie attribute
has false value you should check C<$respE<gt>error> yourself. Default is false.
=head1 METHODS
C<Mojo::SMTP::Client> inherits all methods from L<Mojo::EventEmitter> and implements the following new ones
=head2 send
$smtp->send(
from => $mail_from,
to => $rcpt_to,
data => $data,
quit => 1,
$nonblocking ? $cb : ()
);
Send specified commands to SMTP server. Arguments should be C<key =E<gt> value> pairs where C<key> is a command
and C<value> is a value for this command. C<send> understands the following commands:
=over
=item hello
Send greeting to the server. Argument to this command should contain your domain name. Keep in mind, that
C<Mojo::SMTP::Client> will automatically send greeting to the server right after connection if you not specified
C<hello> as first command for C<send>. C<Mojo::SMTP::Client> first tries C<EHLO> command for greeting and if
server doesn't accept it C<Mojo::SMTP::Client> retries with C<HELO> command.
$smtp->send(hello => 'mymail.me');
=item starttls
Upgrades connection from plain to encrypted. Some servers requires this before sending any other commands.
L<IO::Socket::SSL> 0.98+ should be installed for this to work. See also L</tls_ca>, L</tls_cert>, L</tls_key>
attributes
$smtp->tls_ca('/etc/ssl/certs/ca-certificates.crt');
$smtp->send(starttls => 1);
=item auth
Authorize on SMTP server. Argument to this command should be reference to a hash with C<login> and C<password>
keys. Only PLAIN authorization supported for now. You should authorize only once per session
$smtp->send(auth => {login => 'oleg', password => 'qwerty'});
=item from
From which email this message was sent. Value for this cammand should be a string with email
$smtp->send(from => 'root@cpan.org');
=item to
To which email(s) this message should be sent. Value for this cammand should be a string with email
or reference to array with email strings (for more than one recipient)
$smtp->send(to => 'oleg@cpan.org');
$smtp->send(to => ['oleg@cpan.org', 'do_not_reply@cpantesters.org']);
=item reset
After this command server should forget about any started mail transaction and reset it status as it was after response to C<EHLO>/C<HELO>.
Note: transaction considered started after C<MAIL FROM> (C<from>) command.
$smtp->send(reset => 1);
=item data
Email body to be sent. Value for this command should be a string (or reference to a string) with email body or reference to subroutine
each call of which should return some chunk of the email as string (or reference to a string) and empty string (or reference to empty string)
at the end (useful to send big emails in memory-efficient way)
$smtp->send(data => "Subject: This is my first message\r\n\r\nSent from Mojolicious app");
$smtp->send(data => sub { sysread(DATA, my $buf, 1024); $buf });
=item quit
Send C<QUIT> command to SMTP server which will close the connection. So for the next use of this server connection will be
reestablished. If you want to send several emails with this server it will be more efficient to not quit
the connection until last email will be sent.
=back
For non-blocking usage last argument to C<send> should be reference to subroutine which will be called when result will
be available. Subroutine arguments will be C<($smtp, $resp)>. Where C<$resp> is object of L<Mojo::SMTP::Client::Response> class.
First you should check C<$resp-E<gt>error> - if it has true value this means that it was error somewhere while sending.
If C<error> has false value you can get code and message for response to last command with C<$resp-E<gt>code> (number) and
C<$resp-E<gt>message> (string).
For blocking usage C<$resp> will be returned as result of C<$smtp-E<gt>send> call. C<$resp> is the same as for
non-blocking result. If L</autodie> attribute has true value C<send> will throw an exception on any error.
Which will be one of C<Mojo::SMTP::Client::Exception::*>.
B<Note>. For SMTP protocol it is important to send commands in certain order. Also C<send> will send all commands in order you are
specified. So, it is important to pass arguments to C<send> in right order. For basic usage this will always be:
C<from -E<gt> to -E<gt> data -E<gt> quit>. You should also know that it is absolutely correct to specify several non-unique commands.
For example you can send several emails with one C<send> call:
$smtp->send(
from => 'someone@somewhere.com',
to => 'somebody@somewhere.net',
data => $mail_1,
from => 'frodo@somewhere.com',
to => 'garry@somewhere.net',
data => $mail_2,
quit => 1
);
B<Note>. Connection to SMTP server will be made on first C<send> or for each C<send> when socket connection not already estabilished
(was closed by C<QUIT> command or errors in the stream). It is error to make several simultaneous non-blocking C<send> calls on the
same C<Mojo::SMTP::Client>, because each client has one global stream per client. So, you need to create several
clients to make simultaneous sending.
=head2 prepend_cmd
$smtp->prepend_cmd(reset => 1, starttls => 1);
Prepend specified commands to the queue, so the next command sent to the server will be the first you specified in C<prepend_cmd>.
You can prepend commands only when sending already in progress and there are commands in the queue. So, the most common place to call
C<prepend_cmd> is inside C<response> event handler. For example this is how we can say "start SSL session if server supports it":
$smtp->on(response => sub {
my ($smtp, $cmd, $resp) = @_;
if ($cmd == Mojo::SMTP::Client::CMD_EHLO && $resp->message =~ /STARTTLS/i) {
$smtp->prepend_cmd(starttls => 1);
}
});
$smtp->send(
from => $from,
to => $to,
data => $data,
quit => 1
);
C<prepend_cmd> accepts same commands as L</send>.
=head1 CONSTANTS
C<Mojo::SMTP::Client> has this non-importable constants
CMD_CONNECT # client connected to SMTP server
CMD_EHLO # client sent EHLO command
CMD_HELO # client sent HELO command
CMD_STARTTLS # client sent STARTTLS command
CMD_AUTH # client sent AUTH command
CMD_FROM # client sent MAIL FROM command
CMD_TO # client sent RCPT TO command
CMD_DATA # client sent DATA command
CMD_DATA_END # client sent . command
CMD_RESET # client sent RSET command
CMD_QUIT # client sent QUIT command
=head1 VARIABLES
C<Mojo::SMTP::Client> has this non-importable variables
=over
=item %CMD
Get human readable command by it constant
print $Mojo::SMTP::Client::CMD{ Mojo::SMTP::Client::CMD_EHLO };
=back
=head1 COOKBOOK
=head2 How to send simple ASCII message
ASCII message is simple enough, so you can generate it by hand
$smtp->send(
from => 'me@home.org',
to => 'you@work.org',
data => join(
"\r\n",
'MIME-Version: 1.0',
'Subject: Subject of the message',
'From: me@home.org',
'To: you@work.org',
'Content-Type: text/plain; charset=UTF-8',
'',
'Text of the message'
)
);
However it is not recommended to generate emails by hand if you are not
familar with MIME standard. For more convenient approaches see below.
=head2 How to send text message with possible non-ASCII characters
For more convinient way to generate emails we can use some email generators
available on CPAN. L<MIME::Lite> for example. With such modules we can get
email as a string and send it with C<Mojo::SMTP::Client>
use MIME::Lite;
use Encode qw(encode decode);
my $msg = MIME::Lite->new(
Type => 'text',
From => 'me@home.org',
To => 'you@work.org',
Subject => encode('MIME-Header', decode('utf-8', '世界, 労働, 5月!')),
Data => 'Novosibirsk (Russian: Новосибирск; IPA: [nəvəsʲɪˈbʲirsk]) is the third most populous '.
'city in Russia after Moscow and St. Petersburg and the most populous city in Asian Russia'
);
$msg->attr('content-type.charset' => 'UTF-8');
$smtp->send(
from => 'me@home.org',
to => 'you@work.org',
data => $msg->as_string
);
=head2 How to send message with attachment
This is also simple with help of L<MIME::Lite>
use MIME::Lite;
my $msg = MIME::Lite->new(
Type => 'multipart/mixed',
From => 'me@home.org',
To => 'you@work.org',
Subject => 'statistic for 10.03.2015'
);
$msg->attach(Path => '/home/kate/stat/10032015.xlsx', Disposition => 'attachment', Type => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
$smtp->send(
from => 'me@home.org',
to => 'you@work.org',
data => $msg->as_string
);
=head2 How to send message with BIG attachment
It will be not cool to get message with 50 mb attachment into memory before sending.
Fortunately with help of L<MIME::Lite> and L<MIME::Lite::Generator> we can generate
our email by small portions. As you remember C<data> command accepts subroutine reference
as argument, so it will be super easy to send our big email in memory-efficient way
use MIME::Lite;
my $msg = MIME::Lite->new(
Type => 'multipart/mixed',
From => 'me@home.org',
To => 'you@work.org',
Subject => 'my home video'
);
# Note: MIME::Lite will not load this file into memory
$msg->attach(Path => '/home/kate/videos/beach.avi', Disposition => 'attachment', Type => "video/msvideo");
my $generator = MIME::Lite::Generator->new($msg);
$smtp->send(
from => 'me@home.org',
to => 'you@work.org',
data => sub { $generator->get() }
);
=head2 How to send message using public email services like Gmail
Most such services provides access via SMTP in addition to web interface, but needs authorization. To protect your
login and password most of them requires to start encrypted session (by upgrading plain connection with C<starttls>
or by initial C<tls> connection). For example Gmail supports both this ways:
# make plain connection to port 25
my $smtp = Mojo::SMTP::Client->new(address => 'smtp.gmail.com');
# and upgrade it to TLS with starttls
$smtp->send(
starttls => 1,
auth => {login => $login, password => $password},
from => $from,
to => $to,
data => $msg,
quit => 1
);
# or make initial TLS connection to port 465
my $smtp = Mojo::SMTP::Client->new(address => 'smtp.gmail.com', tls => 1);
# no need to use starttls
$smtp->send(
auth => {login => $login, password => $password},
from => $from,
to => $to,
data => $msg,
quit => 1
);
=head2 How to send message directly, without using of MTAs such as sendmail, postfix, exim, ...
Sometimes it is more suitable to send message directly to SMTP server of recipient. For example
if you haven't any MTA available or want to check recipient's server responses (e.g. to know is
such user exists on this server [see L<Mojo::Email::Checker::SMTP>]). First you need to know address
of necessary SMTP server. We'll get it with help of L<Net::DNS>. Then we'll send it as usual
# will use non-blocking approach in this example
use strict;
use MIME::Lite;
use Net::DNS;
use Mojo::SMTP::Client;
use Mojo::IOLoop;
use constant TO => 'oleg@cpan.org';
my $loop = Mojo::IOLoop->singleton;
my $resolver = Net::DNS::Resolver->new();
my ($domain) = TO =~ /@(.+)/;
# Get MX records
my $sock = $resolver->bgsend($domain, 'MX');
$loop->reactor->io($sock => sub {
my $packet = $resolver->bgread($sock);
$loop->reactor->remove($sock);
my @mx;
if ($packet) {
for my $rec ($packet->answer) {
push @mx, $rec->exchange if $rec->type eq 'MX';
}
}
# Will try with first or plain domain name if no mx records found
my $address = @mx ? $mx[0] : $domain;
my $smtp = Mojo::SMTP::Client->new(
address => $address,
# it is important to properly identify yourself