1# Net::SMTP.pm
2#
3# Copyright (C) 1995-2004 Graham Barr.  All rights reserved.
4# Copyright (C) 2013-2016, 2020 Steve Hay.  All rights reserved.
5# This module is free software; you can redistribute it and/or modify it under
6# the same terms as Perl itself, i.e. under the terms of either the GNU General
7# Public License or the Artistic License, as specified in the F<LICENCE> file.
8
9package Net::SMTP;
10
11use 5.008001;
12
13use strict;
14use warnings;
15
16use Carp;
17use IO::Socket;
18use Net::Cmd;
19use Net::Config;
20use Socket;
21
22our $VERSION = "3.13";
23
24# Code for detecting if we can use SSL
25my $ssl_class = eval {
26  require IO::Socket::SSL;
27  # first version with default CA on most platforms
28  no warnings 'numeric';
29  IO::Socket::SSL->VERSION(2.007);
30} && 'IO::Socket::SSL';
31
32my $nossl_warn = !$ssl_class &&
33  'To use SSL please install IO::Socket::SSL with version>=2.007';
34
35# Code for detecting if we can use IPv6
36my $family_key = 'Domain';
37my $inet6_class = eval {
38  require IO::Socket::IP;
39  no warnings 'numeric';
40  IO::Socket::IP->VERSION(0.25) || die;
41  $family_key = 'Family';
42} && 'IO::Socket::IP' || eval {
43  require IO::Socket::INET6;
44  no warnings 'numeric';
45  IO::Socket::INET6->VERSION(2.62);
46} && 'IO::Socket::INET6';
47
48sub can_ssl   { $ssl_class };
49sub can_inet6 { $inet6_class };
50
51our @ISA = ('Net::Cmd', $inet6_class || 'IO::Socket::INET');
52
53sub new {
54  my $self = shift;
55  my $type = ref($self) || $self;
56  my ($host, %arg);
57  if (@_ % 2) {
58    $host = shift;
59    %arg  = @_;
60  }
61  else {
62    %arg  = @_;
63    $host = delete $arg{Host};
64  }
65
66  if ($arg{SSL}) {
67    # SSL from start
68    die $nossl_warn if !$ssl_class;
69    $arg{Port} ||= 465;
70  }
71
72  my $hosts = defined $host ? $host : $NetConfig{smtp_hosts};
73  my $obj;
74
75  $arg{Timeout} = 120 if ! defined $arg{Timeout};
76
77  foreach my $h (@{ref($hosts) ? $hosts : [$hosts]}) {
78    $obj = $type->SUPER::new(
79      PeerAddr => ($host = $h),
80      PeerPort => $arg{Port} || 'smtp(25)',
81      LocalAddr => $arg{LocalAddr},
82      LocalPort => $arg{LocalPort},
83      $family_key => $arg{Domain} || $arg{Family},
84      Proto     => 'tcp',
85      Timeout   => $arg{Timeout}
86      )
87      and last;
88  }
89
90  return
91    unless defined $obj;
92
93  ${*$obj}{'net_smtp_arg'} = \%arg;
94  ${*$obj}{'net_smtp_host'} = $host;
95
96  if ($arg{SSL}) {
97    Net::SMTP::_SSL->start_SSL($obj,%arg)
98      or return;
99  }
100
101  $obj->autoflush(1);
102
103  $obj->debug(exists $arg{Debug} ? $arg{Debug} : undef);
104
105  unless ($obj->response() == CMD_OK) {
106    my $err = ref($obj) . ": " . $obj->code . " " . $obj->message;
107    $obj->close();
108    $@ = $err;
109    return;
110  }
111
112  ${*$obj}{'net_smtp_exact_addr'} = $arg{ExactAddresses};
113
114  (${*$obj}{'net_smtp_banner'}) = $obj->message;
115  (${*$obj}{'net_smtp_domain'}) = $obj->message =~ /\A\s*(\S+)/;
116
117  if (!exists $arg{SendHello} || $arg{SendHello}) {
118    unless ($obj->hello($arg{Hello} || "")) {
119      my $err = ref($obj) . ": " . $obj->code . " " . $obj->message;
120      $obj->close();
121      $@ = $err;
122      return;
123    }
124  }
125
126  $obj;
127}
128
129
130sub host {
131  my $me = shift;
132  ${*$me}{'net_smtp_host'};
133}
134
135##
136## User interface methods
137##
138
139
140sub banner {
141  my $me = shift;
142
143  return ${*$me}{'net_smtp_banner'} || undef;
144}
145
146
147sub domain {
148  my $me = shift;
149
150  return ${*$me}{'net_smtp_domain'} || undef;
151}
152
153
154sub etrn {
155  my $self = shift;
156  defined($self->supports('ETRN', 500, ["Command unknown: 'ETRN'"]))
157    && $self->_ETRN(@_);
158}
159
160
161sub auth {
162  my ($self, $username, $password) = @_;
163
164  eval {
165    require MIME::Base64;
166    require Authen::SASL;
167  } or $self->set_status(500, ["Need MIME::Base64 and Authen::SASL todo auth"]), return 0;
168
169  my $mechanisms = $self->supports('AUTH', 500, ["Command unknown: 'AUTH'"]);
170  return unless defined $mechanisms;
171
172  my $sasl;
173
174  if (ref($username) and UNIVERSAL::isa($username, 'Authen::SASL')) {
175    $sasl = $username;
176    my $requested_mechanisms = $sasl->mechanism();
177    if (! defined($requested_mechanisms) || $requested_mechanisms eq '') {
178      $sasl->mechanism($mechanisms);
179    }
180  }
181  else {
182    die "auth(username, password)" if not length $username;
183    $sasl = Authen::SASL->new(
184      mechanism => $mechanisms,
185      callback  => {
186        user     => $username,
187        pass     => $password,
188        authname => $username,
189      },
190      debug => $self->debug
191    );
192  }
193
194  my $client;
195  my $str;
196  do {
197    if ($client) {
198      # $client mechanism failed, so we need to exclude this mechanism from list
199      my $failed_mechanism = $client->mechanism;
200      return unless defined $failed_mechanism;
201      $self->debug_text("Auth mechanism failed: $failed_mechanism")
202        if $self->debug;
203      $mechanisms =~ s/\b\Q$failed_mechanism\E\b//;
204      return unless $mechanisms =~ /\S/;
205      $sasl->mechanism($mechanisms);
206    }
207
208    # We should probably allow the user to pass the host, but I don't
209    # currently know and SASL mechanisms that are used by smtp that need it
210
211    $client = $sasl->client_new('smtp', ${*$self}{'net_smtp_host'}, 0);
212    $str    = $client->client_start;
213  } while (!defined $str);
214
215  # We don't support sasl mechanisms that encrypt the socket traffic.
216  # todo that we would really need to change the ISA hierarchy
217  # so we don't inherit from IO::Socket, but instead hold it in an attribute
218
219  my @cmd = ("AUTH", $client->mechanism);
220  my $code;
221
222  push @cmd, MIME::Base64::encode_base64($str, '')
223    if defined $str and length $str;
224
225  while (($code = $self->command(@cmd)->response()) == CMD_MORE) {
226    my $str2 = MIME::Base64::decode_base64(($self->message)[0]);
227    $self->debug_print(0, "(decoded) " . $str2 . "\n") if $self->debug;
228
229    $str = $client->client_step($str2);
230    @cmd = (
231      MIME::Base64::encode_base64($str, '')
232    );
233
234    $self->debug_print(1, "(decoded) " . $str . "\n") if $self->debug;
235  }
236
237  $code == CMD_OK;
238}
239
240
241sub hello {
242  my $me     = shift;
243  my $domain = shift || "localhost.localdomain";
244  my $ok     = $me->_EHLO($domain);
245  my @msg    = $me->message;
246
247  if ($ok) {
248    my $h = ${*$me}{'net_smtp_esmtp'} = {};
249    foreach my $ln (@msg) {
250      $h->{uc $1} = $2
251        if $ln =~ /([-\w]+)\b[= \t]*([^\n]*)/;
252    }
253  }
254  elsif ($me->status == CMD_ERROR) {
255    @msg = $me->message
256      if $ok = $me->_HELO($domain);
257  }
258
259  return unless $ok;
260  ${*$me}{net_smtp_hello_domain} = $domain;
261
262  $msg[0] =~ /\A\s*(\S+)/;
263  return ($1 || " ");
264}
265
266sub starttls {
267  my $self = shift;
268  $ssl_class or die $nossl_warn;
269  $self->_STARTTLS or return;
270  Net::SMTP::_SSL->start_SSL($self,
271    %{ ${*$self}{'net_smtp_arg'} }, # (ssl) args given in new
272    @_   # more (ssl) args
273  ) or return;
274
275  # another hello after starttls to read new ESMTP capabilities
276  return $self->hello(${*$self}{net_smtp_hello_domain});
277}
278
279
280sub supports {
281  my $self = shift;
282  my $cmd  = uc shift;
283  return ${*$self}{'net_smtp_esmtp'}->{$cmd}
284    if exists ${*$self}{'net_smtp_esmtp'}->{$cmd};
285  $self->set_status(@_)
286    if @_;
287  return;
288}
289
290
291sub _addr {
292  my $self = shift;
293  my $addr = shift;
294  $addr = "" unless defined $addr;
295
296  if (${*$self}{'net_smtp_exact_addr'}) {
297    return $1 if $addr =~ /^\s*(<.*>)\s*$/s;
298  }
299  else {
300    return $1 if $addr =~ /(<[^>]*>)/;
301    $addr =~ s/^\s+|\s+$//sg;
302  }
303
304  "<$addr>";
305}
306
307
308sub mail {
309  my $me   = shift;
310  my $addr = _addr($me, shift);
311  my $opts = "";
312
313  if (@_) {
314    my %opt = @_;
315    my ($k, $v);
316
317    if (exists ${*$me}{'net_smtp_esmtp'}) {
318      my $esmtp = ${*$me}{'net_smtp_esmtp'};
319
320      if (defined($v = delete $opt{Size})) {
321        if (exists $esmtp->{SIZE}) {
322          $opts .= sprintf " SIZE=%d", $v + 0;
323        }
324        else {
325          carp 'Net::SMTP::mail: SIZE option not supported by host';
326        }
327      }
328
329      if (defined($v = delete $opt{Return})) {
330        if (exists $esmtp->{DSN}) {
331          $opts .= " RET=" . ((uc($v) eq "FULL") ? "FULL" : "HDRS");
332        }
333        else {
334          carp 'Net::SMTP::mail: DSN option not supported by host';
335        }
336      }
337
338      if (defined($v = delete $opt{Bits})) {
339        if ($v eq "8") {
340          if (exists $esmtp->{'8BITMIME'}) {
341            $opts .= " BODY=8BITMIME";
342          }
343          else {
344            carp 'Net::SMTP::mail: 8BITMIME option not supported by host';
345          }
346        }
347        elsif ($v eq "binary") {
348          if (exists $esmtp->{'BINARYMIME'} && exists $esmtp->{'CHUNKING'}) {
349            $opts .= " BODY=BINARYMIME";
350            ${*$me}{'net_smtp_chunking'} = 1;
351          }
352          else {
353            carp 'Net::SMTP::mail: BINARYMIME option not supported by host';
354          }
355        }
356        elsif (exists $esmtp->{'8BITMIME'} or exists $esmtp->{'BINARYMIME'}) {
357          $opts .= " BODY=7BIT";
358        }
359        else {
360          carp 'Net::SMTP::mail: 8BITMIME and BINARYMIME options not supported by host';
361        }
362      }
363
364      if (defined($v = delete $opt{Transaction})) {
365        if (exists $esmtp->{CHECKPOINT}) {
366          $opts .= " TRANSID=" . _addr($me, $v);
367        }
368        else {
369          carp 'Net::SMTP::mail: CHECKPOINT option not supported by host';
370        }
371      }
372
373      if (defined($v = delete $opt{Envelope})) {
374        if (exists $esmtp->{DSN}) {
375          $v =~ s/([^\041-\176]|=|\+)/sprintf "+%02X", ord($1)/sge;
376          $opts .= " ENVID=$v";
377        }
378        else {
379          carp 'Net::SMTP::mail: DSN option not supported by host';
380        }
381      }
382
383      if (defined($v = delete $opt{ENVID})) {
384
385        # expected to be in a format as required by RFC 3461, xtext-encoded
386        if (exists $esmtp->{DSN}) {
387          $opts .= " ENVID=$v";
388        }
389        else {
390          carp 'Net::SMTP::mail: DSN option not supported by host';
391        }
392      }
393
394      if (defined($v = delete $opt{AUTH})) {
395
396        # expected to be in a format as required by RFC 2554,
397        # rfc2821-quoted and xtext-encoded, or <>
398        if (exists $esmtp->{AUTH}) {
399          $v = '<>' if !defined($v) || $v eq '';
400          $opts .= " AUTH=$v";
401        }
402        else {
403          carp 'Net::SMTP::mail: AUTH option not supported by host';
404        }
405      }
406
407      if (defined($v = delete $opt{XVERP})) {
408        if (exists $esmtp->{'XVERP'}) {
409          $opts .= " XVERP";
410        }
411        else {
412          carp 'Net::SMTP::mail: XVERP option not supported by host';
413        }
414      }
415
416      carp 'Net::SMTP::recipient: unknown option(s) ' . join(" ", keys %opt) . ' - ignored'
417        if scalar keys %opt;
418    }
419    else {
420      carp 'Net::SMTP::mail: ESMTP not supported by host - options discarded :-(';
421    }
422  }
423
424  $me->_MAIL("FROM:" . $addr . $opts);
425}
426
427
428sub send          { my $me = shift; $me->_SEND("FROM:" . _addr($me, $_[0])) }
429sub send_or_mail  { my $me = shift; $me->_SOML("FROM:" . _addr($me, $_[0])) }
430sub send_and_mail { my $me = shift; $me->_SAML("FROM:" . _addr($me, $_[0])) }
431
432
433sub reset {
434  my $me = shift;
435
436  $me->dataend()
437    if (exists ${*$me}{'net_smtp_lastch'});
438
439  $me->_RSET();
440}
441
442
443sub recipient {
444  my $smtp     = shift;
445  my $opts     = "";
446  my $skip_bad = 0;
447
448  if (@_ && ref($_[-1])) {
449    my %opt = %{pop(@_)};
450    my $v;
451
452    $skip_bad = delete $opt{'SkipBad'};
453
454    if (exists ${*$smtp}{'net_smtp_esmtp'}) {
455      my $esmtp = ${*$smtp}{'net_smtp_esmtp'};
456
457      if (defined($v = delete $opt{Notify})) {
458        if (exists $esmtp->{DSN}) {
459          $opts .= " NOTIFY=" . join(",", map { uc $_ } @$v);
460        }
461        else {
462          carp 'Net::SMTP::recipient: DSN option not supported by host';
463        }
464      }
465
466      if (defined($v = delete $opt{ORcpt})) {
467        if (exists $esmtp->{DSN}) {
468          $opts .= " ORCPT=" . $v;
469        }
470        else {
471          carp 'Net::SMTP::recipient: DSN option not supported by host';
472        }
473      }
474
475      carp 'Net::SMTP::recipient: unknown option(s) ' . join(" ", keys %opt) . ' - ignored'
476        if scalar keys %opt;
477    }
478    elsif (%opt) {
479      carp 'Net::SMTP::recipient: ESMTP not supported by host - options discarded :-(';
480    }
481  }
482
483  my @ok;
484  foreach my $addr (@_) {
485    if ($smtp->_RCPT("TO:" . _addr($smtp, $addr) . $opts)) {
486      push(@ok, $addr) if $skip_bad;
487    }
488    elsif (!$skip_bad) {
489      return 0;
490    }
491  }
492
493  return $skip_bad ? @ok : 1;
494}
495
496BEGIN {
497  *to  = \&recipient;
498  *cc  = \&recipient;
499  *bcc = \&recipient;
500}
501
502
503sub data {
504  my $me = shift;
505
506  if (exists ${*$me}{'net_smtp_chunking'}) {
507    carp 'Net::SMTP::data: CHUNKING extension in use, must call bdat instead';
508  }
509  else {
510    my $ok = $me->_DATA() && $me->datasend(@_);
511
512    $ok && @_
513      ? $me->dataend
514      : $ok;
515  }
516}
517
518
519sub bdat {
520  my $me = shift;
521
522  if (exists ${*$me}{'net_smtp_chunking'}) {
523    my $data = shift;
524
525    $me->_BDAT(length $data)
526      && $me->rawdatasend($data)
527      && $me->response() == CMD_OK;
528  }
529  else {
530    carp 'Net::SMTP::bdat: CHUNKING extension is not in use, call data instead';
531  }
532}
533
534
535sub bdatlast {
536  my $me = shift;
537
538  if (exists ${*$me}{'net_smtp_chunking'}) {
539    my $data = shift;
540
541    $me->_BDAT(length $data, "LAST")
542      && $me->rawdatasend($data)
543      && $me->response() == CMD_OK;
544  }
545  else {
546    carp 'Net::SMTP::bdat: CHUNKING extension is not in use, call data instead';
547  }
548}
549
550
551sub datafh {
552  my $me = shift;
553  return unless $me->_DATA();
554  return $me->tied_fh;
555}
556
557
558sub expand {
559  my $me = shift;
560
561  $me->_EXPN(@_)
562    ? ($me->message)
563    : ();
564}
565
566
567sub verify { shift->_VRFY(@_) }
568
569
570sub help {
571  my $me = shift;
572
573  $me->_HELP(@_)
574    ? scalar $me->message
575    : undef;
576}
577
578
579sub quit {
580  my $me = shift;
581
582  $me->_QUIT;
583  $me->close;
584}
585
586
587sub DESTROY {
588
589  # ignore
590}
591
592##
593## RFC821 commands
594##
595
596
597sub _EHLO { shift->command("EHLO", @_)->response() == CMD_OK }
598sub _HELO { shift->command("HELO", @_)->response() == CMD_OK }
599sub _MAIL { shift->command("MAIL", @_)->response() == CMD_OK }
600sub _RCPT { shift->command("RCPT", @_)->response() == CMD_OK }
601sub _SEND { shift->command("SEND", @_)->response() == CMD_OK }
602sub _SAML { shift->command("SAML", @_)->response() == CMD_OK }
603sub _SOML { shift->command("SOML", @_)->response() == CMD_OK }
604sub _VRFY { shift->command("VRFY", @_)->response() == CMD_OK }
605sub _EXPN { shift->command("EXPN", @_)->response() == CMD_OK }
606sub _HELP { shift->command("HELP", @_)->response() == CMD_OK }
607sub _RSET { shift->command("RSET")->response() == CMD_OK }
608sub _NOOP { shift->command("NOOP")->response() == CMD_OK }
609sub _QUIT { shift->command("QUIT")->response() == CMD_OK }
610sub _DATA { shift->command("DATA")->response() == CMD_MORE }
611sub _BDAT { shift->command("BDAT", @_) }
612sub _TURN { shift->unsupported(@_); }
613sub _ETRN { shift->command("ETRN", @_)->response() == CMD_OK }
614sub _AUTH { shift->command("AUTH", @_)->response() == CMD_OK }
615sub _STARTTLS { shift->command("STARTTLS")->response() == CMD_OK }
616
617
618{
619  package Net::SMTP::_SSL;
620  our @ISA = ( $ssl_class ? ($ssl_class):(), 'Net::SMTP' );
621  sub starttls { die "SMTP connection is already in SSL mode" }
622  sub start_SSL {
623    my ($class,$smtp,%arg) = @_;
624    delete @arg{ grep { !m{^SSL_} } keys %arg };
625    ( $arg{SSL_verifycn_name} ||= $smtp->host )
626        =~s{(?<!:):[\w()]+$}{}; # strip port
627    $arg{SSL_hostname} = $arg{SSL_verifycn_name}
628        if ! defined $arg{SSL_hostname} && $class->can_client_sni;
629    $arg{SSL_verifycn_scheme} ||= 'smtp';
630    my $ok = $class->SUPER::start_SSL($smtp,%arg);
631    $@ = $ssl_class->errstr if !$ok;
632    return $ok;
633  }
634}
635
636
637
6381;
639
640__END__
641
642=head1 NAME
643
644Net::SMTP - Simple Mail Transfer Protocol Client
645
646=head1 SYNOPSIS
647
648    use Net::SMTP;
649
650    # Constructors
651    $smtp = Net::SMTP->new('mailhost');
652    $smtp = Net::SMTP->new('mailhost', Timeout => 60);
653
654=head1 DESCRIPTION
655
656This module implements a client interface to the SMTP and ESMTP
657protocol, enabling a perl5 application to talk to SMTP servers. This
658documentation assumes that you are familiar with the concepts of the
659SMTP protocol described in RFC2821.
660With L<IO::Socket::SSL> installed it also provides support for implicit and
661explicit TLS encryption, i.e. SMTPS or SMTP+STARTTLS.
662
663The Net::SMTP class is a subclass of Net::Cmd and (depending on avaibility) of
664IO::Socket::IP, IO::Socket::INET6 or IO::Socket::INET.
665
666=head2 Class Methods
667
668=over 4
669
670=item C<new([$host][, %options])>
671
672This is the constructor for a new Net::SMTP object. C<$host> is the
673name of the remote host to which an SMTP connection is required.
674
675On failure C<undef> will be returned and C<$@> will contain the reason
676for the failure.
677
678C<$host> is optional. If C<$host> is not given then it may instead be
679passed as the C<Host> option described below. If neither is given then
680the C<SMTP_Hosts> specified in C<Net::Config> will be used.
681
682C<%options> are passed in a hash like fashion, using key and value pairs.
683Possible options are:
684
685B<Hello> - SMTP requires that you identify yourself. This option
686specifies a string to pass as your mail domain. If not given localhost.localdomain
687will be used.
688
689B<SendHello> - If false then the EHLO (or HELO) command that is normally sent
690when constructing the object will not be sent. In that case the command will
691have to be sent manually by calling C<hello()> instead.
692
693B<Host> - SMTP host to connect to. It may be a single scalar (hostname[:port]),
694as defined for the C<PeerAddr> option in L<IO::Socket::INET>, or a reference to
695an array with hosts to try in turn. The L</host> method will return the value
696which was used to connect to the host.
697Format - C<PeerHost> from L<IO::Socket::INET> new method.
698
699B<Port> - port to connect to.
700Default - 25 for plain SMTP and 465 for immediate SSL.
701
702B<SSL> - If the connection should be done from start with SSL, contrary to later
703upgrade with C<starttls>.
704You can use SSL arguments as documented in L<IO::Socket::SSL>, but it will
705usually use the right arguments already.
706
707B<LocalAddr> and B<LocalPort> - These parameters are passed directly
708to IO::Socket to allow binding the socket to a specific local address and port.
709
710B<Domain> - This parameter is passed directly to IO::Socket and makes it
711possible to enforce IPv4 connections even if L<IO::Socket::IP> is used as super
712class. Alternatively B<Family> can be used.
713
714B<Timeout> - Maximum time, in seconds, to wait for a response from the
715SMTP server (default: 120)
716
717B<ExactAddresses> - If true then all C<$address> arguments must be as
718defined by C<addr-spec> in RFC2822. If not given, or false, then
719Net::SMTP will attempt to extract the address from the value passed.
720
721B<Debug> - Enable debugging information
722
723Example:
724
725    $smtp = Net::SMTP->new('mailhost',
726                           Hello => 'my.mail.domain',
727                           Timeout => 30,
728                           Debug   => 1,
729                          );
730
731    # the same
732    $smtp = Net::SMTP->new(
733                           Host => 'mailhost',
734                           Hello => 'my.mail.domain',
735                           Timeout => 30,
736                           Debug   => 1,
737                          );
738
739    # the same with direct SSL
740    $smtp = Net::SMTP->new('mailhost',
741                           Hello => 'my.mail.domain',
742                           Timeout => 30,
743                           Debug   => 1,
744                           SSL     => 1,
745                          );
746
747    # Connect to the default server from Net::config
748    $smtp = Net::SMTP->new(
749                           Hello => 'my.mail.domain',
750                           Timeout => 30,
751                          );
752
753=back
754
755=head1 Object Methods
756
757Unless otherwise stated all methods return either a I<true> or I<false>
758value, with I<true> meaning that the operation was a success. When a method
759states that it returns a value, failure will be returned as I<undef> or an
760empty list.
761
762C<Net::SMTP> inherits from C<Net::Cmd> so methods defined in C<Net::Cmd> may
763be used to send commands to the remote SMTP server in addition to the methods
764documented here.
765
766=over 4
767
768=item C<banner()>
769
770Returns the banner message which the server replied with when the
771initial connection was made.
772
773=item C<domain()>
774
775Returns the domain that the remote SMTP server identified itself as during
776connection.
777
778=item C<hello($domain)>
779
780Tell the remote server the mail domain which you are in using the EHLO
781command (or HELO if EHLO fails).  Since this method is invoked
782automatically when the Net::SMTP object is constructed the user should
783normally not have to call it manually.
784
785=item C<host()>
786
787Returns the value used by the constructor, and passed to IO::Socket::INET,
788to connect to the host.
789
790=item C<etrn($domain)>
791
792Request a queue run for the C<$domain> given.
793
794=item C<starttls(%sslargs)>
795
796Upgrade existing plain connection to SSL.
797You can use SSL arguments as documented in L<IO::Socket::SSL>, but it will
798usually use the right arguments already.
799
800=item C<auth($username, $password)>
801
802=item C<auth($sasl)>
803
804Attempt SASL authentication. Requires Authen::SASL module. The first form
805constructs a new Authen::SASL object using the given username and password;
806the second form uses the given Authen::SASL object.
807
808=item C<mail($address[, %options])>
809
810=item C<send($address)>
811
812=item C<send_or_mail($address)>
813
814=item C<send_and_mail($address)>
815
816Send the appropriate command to the server MAIL, SEND, SOML or SAML. C<$address>
817is the address of the sender. This initiates the sending of a message. The
818method C<recipient> should be called for each address that the message is to
819be sent to.
820
821The C<mail> method can take some additional ESMTP C<%options> which is passed
822in hash like fashion, using key and value pairs.  Possible options are:
823
824 Size        => <bytes>
825 Return      => "FULL" | "HDRS"
826 Bits        => "7" | "8" | "binary"
827 Transaction => <ADDRESS>
828 Envelope    => <ENVID>     # xtext-encodes its argument
829 ENVID       => <ENVID>     # similar to Envelope, but expects argument encoded
830 XVERP       => 1
831 AUTH        => <submitter> # encoded address according to RFC 2554
832
833The C<Return> and C<Envelope> parameters are used for DSN (Delivery
834Status Notification).
835
836The submitter address in C<AUTH> option is expected to be in a format as
837required by RFC 2554, in an RFC2821-quoted form and xtext-encoded, or <> .
838
839=item C<reset()>
840
841Reset the status of the server. This may be called after a message has been
842initiated, but before any data has been sent, to cancel the sending of the
843message.
844
845=item C<recipient($address[, $address[, ...]][, %options])>
846
847Notify the server that the current message should be sent to all of the
848addresses given. Each address is sent as a separate command to the server.
849Should the sending of any address result in a failure then the process is
850aborted and a I<false> value is returned. It is up to the user to call
851C<reset> if they so desire.
852
853The C<recipient> method can also pass additional case-sensitive C<%options> as an
854anonymous hash using key and value pairs.  Possible options are:
855
856  Notify  => ['NEVER'] or ['SUCCESS','FAILURE','DELAY']  (see below)
857  ORcpt   => <ORCPT>
858  SkipBad => 1        (to ignore bad addresses)
859
860If C<SkipBad> is true the C<recipient> will not return an error when a bad
861address is encountered and it will return an array of addresses that did
862succeed.
863
864  $smtp->recipient($recipient1,$recipient2);  # Good
865  $smtp->recipient($recipient1,$recipient2, { SkipBad => 1 });  # Good
866  $smtp->recipient($recipient1,$recipient2, { Notify => ['FAILURE','DELAY'], SkipBad => 1 });  # Good
867  @goodrecips=$smtp->recipient(@recipients, { Notify => ['FAILURE'], SkipBad => 1 });  # Good
868  $smtp->recipient("$recipient,$recipient2"); # BAD
869
870Notify is used to request Delivery Status Notifications (DSNs), but your
871SMTP/ESMTP service may not respect this request depending upon its version and
872your site's SMTP configuration.
873
874Leaving out the Notify option usually defaults an SMTP service to its default
875behavior equivalent to ['FAILURE'] notifications only, but again this may be
876dependent upon your site's SMTP configuration.
877
878The NEVER keyword must appear by itself if used within the Notify option and "requests
879that a DSN not be returned to the sender under any conditions."
880
881  {Notify => ['NEVER']}
882
883  $smtp->recipient(@recipients, { Notify => ['NEVER'], SkipBad => 1 });  # Good
884
885You may use any combination of these three values 'SUCCESS','FAILURE','DELAY' in
886the anonymous array reference as defined by RFC3461 (see
887L<https://www.ietf.org/rfc/rfc3461.txt> for more information.  Note: quotations
888in this topic from same.).
889
890A Notify parameter of 'SUCCESS' or 'FAILURE' "requests that a DSN be issued on
891successful delivery or delivery failure, respectively."
892
893A Notify parameter of 'DELAY' "indicates the sender's willingness to receive
894delayed DSNs.  Delayed DSNs may be issued if delivery of a message has been
895delayed for an unusual amount of time (as determined by the Message Transfer
896Agent (MTA) at which the message is delayed), but the final delivery status
897(whether successful or failure) cannot be determined.  The absence of the DELAY
898keyword in a NOTIFY parameter requests that a "delayed" DSN NOT be issued under
899any conditions."
900
901  {Notify => ['SUCCESS','FAILURE','DELAY']}
902
903  $smtp->recipient(@recipients, { Notify => ['FAILURE','DELAY'], SkipBad => 1 });  # Good
904
905ORcpt is also part of the SMTP DSN extension according to RFC3461.
906It is used to pass along the original recipient that the mail was first
907sent to.  The machine that generates a DSN will use this address to inform
908the sender, because he can't know if recipients get rewritten by mail servers.
909It is expected to be in a format as required by RFC3461, xtext-encoded.
910
911=item C<to($address[, $address[, ...]])>
912
913=item C<cc($address[, $address[, ...]])>
914
915=item C<bcc($address[, $address[, ...]])>
916
917Synonyms for C<recipient>.
918
919=item C<data([$data])>
920
921Initiate the sending of the data from the current message.
922
923C<$data> may be a reference to a list or a list and must be encoded by the
924caller to octets of whatever encoding is required, e.g. by using the Encode
925module's C<encode()> function.
926
927If specified the contents of C<$data> and a termination string C<".\r\n"> is
928sent to the server. The result will be true if the data was accepted.
929
930If C<$data> is not specified then the result will indicate that the server
931wishes the data to be sent. The data must then be sent using the C<datasend>
932and C<dataend> methods described in L<Net::Cmd>.
933
934=item C<bdat($data)>
935
936=item C<bdatlast($data)>
937
938Use the alternate C<$data> command "BDAT" of the data chunking service extension
939defined in RFC1830 for efficiently sending large MIME messages.
940
941=item C<expand($address)>
942
943Request the server to expand the given address Returns an array
944which contains the text read from the server.
945
946=item C<verify($address)>
947
948Verify that C<$address> is a legitimate mailing address.
949
950Most sites usually disable this feature in their SMTP service configuration.
951Use "Debug => 1" option under new() to see if disabled.
952
953=item C<help([$subject])>
954
955Request help text from the server. Returns the text or undef upon failure
956
957=item C<quit()>
958
959Send the QUIT command to the remote SMTP server and close the socket connection.
960
961=item C<can_inet6()>
962
963Returns whether we can use IPv6.
964
965=item C<can_ssl()>
966
967Returns whether we can use SSL.
968
969=back
970
971=head2 Addresses
972
973Net::SMTP attempts to DWIM with addresses that are passed. For
974example an application might extract The From: line from an email
975and pass that to mail(). While this may work, it is not recommended.
976The application should really use a module like L<Mail::Address>
977to extract the mail address and pass that.
978
979If C<ExactAddresses> is passed to the constructor, then addresses
980should be a valid rfc2821-quoted address, although Net::SMTP will
981accept the address surrounded by angle brackets.
982
983 funny user@domain      WRONG
984 "funny user"@domain    RIGHT, recommended
985 <"funny user"@domain>  OK
986
987=head1 EXAMPLES
988
989This example prints the mail domain name of the SMTP server known as mailhost:
990
991    #!/usr/local/bin/perl -w
992
993    use Net::SMTP;
994
995    $smtp = Net::SMTP->new('mailhost');
996    print $smtp->domain,"\n";
997    $smtp->quit;
998
999This example sends a small message to the postmaster at the SMTP server
1000known as mailhost:
1001
1002    #!/usr/local/bin/perl -w
1003
1004    use Net::SMTP;
1005
1006    my $smtp = Net::SMTP->new('mailhost');
1007
1008    $smtp->mail($ENV{USER});
1009    if ($smtp->to('postmaster')) {
1010     $smtp->data();
1011     $smtp->datasend("To: postmaster\n");
1012     $smtp->datasend("\n");
1013     $smtp->datasend("A simple test message\n");
1014     $smtp->dataend();
1015    } else {
1016     print "Error: ", $smtp->message();
1017    }
1018
1019    $smtp->quit;
1020
1021=head1 EXPORTS
1022
1023I<None>.
1024
1025=head1 KNOWN BUGS
1026
1027See L<https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=libnet>.
1028
1029=head1 SEE ALSO
1030
1031L<Net::Cmd>,
1032L<IO::Socket::SSL>.
1033
1034=head1 AUTHOR
1035
1036Graham Barr E<lt>L<gbarr@pobox.com|mailto:gbarr@pobox.com>E<gt>.
1037
1038Steve Hay E<lt>L<shay@cpan.org|mailto:shay@cpan.org>E<gt> is now maintaining
1039libnet as of version 1.22_02.
1040
1041=head1 COPYRIGHT
1042
1043Copyright (C) 1995-2004 Graham Barr.  All rights reserved.
1044
1045Copyright (C) 2013-2016, 2020 Steve Hay.  All rights reserved.
1046
1047=head1 LICENCE
1048
1049This module is free software; you can redistribute it and/or modify it under the
1050same terms as Perl itself, i.e. under the terms of either the GNU General Public
1051License or the Artistic License, as specified in the F<LICENCE> file.
1052
1053=head1 VERSION
1054
1055Version 3.13
1056
1057=head1 DATE
1058
105923 Dec 2020
1060
1061=head1 HISTORY
1062
1063See the F<Changes> file.
1064
1065=cut
1066