3 # Copyright (c) 1995-1997 Graham Barr <gbarr@pobox.com>. All rights reserved.
4 # This program is free software; you can redistribute it and/or
5 # modify it under the same terms as Perl itself.
12 use vars qw($VERSION @ISA);
19 $VERSION = "2.26"; # $Id: //depot/libnet/Net/SMTP.pm#31 $
21 @ISA = qw(Net::Cmd IO::Socket::INET);
26 my $type = ref($self) || $self;
27 my $host = shift if @_ % 2;
29 my $hosts = defined $host ? $host : $NetConfig{smtp_hosts};
33 foreach $h (@{ref($hosts) ? $hosts : [ $hosts ]})
35 $obj = $type->SUPER::new(PeerAddr => ($host = $h),
36 PeerPort => $arg{Port} || 'smtp(25)',
37 LocalAddr => $arg{LocalAddr},
38 LocalPort => $arg{LocalPort},
40 Timeout => defined $arg{Timeout}
51 $obj->debug(exists $arg{Debug} ? $arg{Debug} : undef);
53 unless ($obj->response() == CMD_OK)
59 ${*$obj}{'net_smtp_exact_addr'} = $arg{ExactAddresses};
60 ${*$obj}{'net_smtp_host'} = $host;
62 (${*$obj}{'net_smtp_banner'}) = $obj->message;
63 (${*$obj}{'net_smtp_domain'}) = $obj->message =~ /\A\s*(\S+)/;
65 unless($obj->hello($arg{Hello} || ""))
75 ## User interface methods
82 return ${*$me}{'net_smtp_banner'} || undef;
89 return ${*$me}{'net_smtp_domain'} || undef;
94 defined($self->supports('ETRN',500,["Command unknown: 'ETRN'"])) &&
99 my ($self, $username, $password) = @_;
101 require MIME::Base64;
102 require Authen::SASL;
104 my $mechanisms = $self->supports('AUTH',500,["Command unknown: 'AUTH'"]);
105 return unless defined $mechanisms;
109 if (ref($username) and UNIVERSAL::isa($username,'Authen::SASL')) {
111 $sasl->mechanism($mechanisms);
114 die "auth(username, password)" if not length $username;
115 $sasl = Authen::SASL->new(mechanism=> $mechanisms,
116 callback => { user => $username,
118 authname => $username,
122 # We should probably allow the user to pass the host, but I don't
123 # currently know and SASL mechanisms that are used by smtp that need it
124 my $client = $sasl->client_new('smtp',${*$self}{'net_smtp_host'},0);
125 my $str = $client->client_start;
126 # We dont support sasl mechanisms that encrypt the socket traffic.
127 # todo that we would really need to change the ISA hierarchy
128 # so we dont inherit from IO::Socket, but instead hold it in an attribute
130 my @cmd = ("AUTH", $client->mechanism);
133 push @cmd, MIME::Base64::encode_base64($str,'')
134 if defined $str and length $str;
136 while (($code = $self->command(@cmd)->response()) == CMD_MORE) {
137 @cmd = (MIME::Base64::encode_base64(
138 $client->client_step(
139 MIME::Base64::decode_base64(
152 my $domain = shift || "localhost.localdomain";
153 my $ok = $me->_EHLO($domain);
154 my @msg = $me->message;
158 my $h = ${*$me}{'net_smtp_esmtp'} = {};
162 if $ln =~ /(\w+)\b[= \t]*([^\n]*)/;
165 elsif($me->status == CMD_ERROR)
168 if $ok = $me->_HELO($domain);
171 return undef unless $ok;
173 $msg[0] =~ /\A\s*(\S+)/;
180 return ${*$self}{'net_smtp_esmtp'}->{$cmd}
181 if exists ${*$self}{'net_smtp_esmtp'}->{$cmd};
182 $self->set_status(@_)
190 $addr = "" unless defined $addr;
192 if (${*$self}{'net_smtp_exact_addr'}) {
193 return $1 if $addr =~ /^\s*(<.*>)\s*$/s;
196 return $1 if $addr =~ /(<[^>]*>)/;
197 $addr =~ s/^\s+|\s+$//sg;
206 my $addr = _addr($me, shift);
214 if(exists ${*$me}{'net_smtp_esmtp'})
216 my $esmtp = ${*$me}{'net_smtp_esmtp'};
218 if(defined($v = delete $opt{Size}))
220 if(exists $esmtp->{SIZE})
222 $opts .= sprintf " SIZE=%d", $v + 0
226 carp 'Net::SMTP::mail: SIZE option not supported by host';
230 if(defined($v = delete $opt{Return}))
232 if(exists $esmtp->{DSN})
234 $opts .= " RET=" . ((uc($v) eq "FULL") ? "FULL" : "HDRS");
238 carp 'Net::SMTP::mail: DSN option not supported by host';
242 if(defined($v = delete $opt{Bits}))
246 if(exists $esmtp->{'8BITMIME'})
248 $opts .= " BODY=8BITMIME";
252 carp 'Net::SMTP::mail: 8BITMIME option not supported by host';
255 elsif($v eq "binary")
257 if(exists $esmtp->{'BINARYMIME'} && exists $esmtp->{'CHUNKING'})
259 $opts .= " BODY=BINARYMIME";
260 ${*$me}{'net_smtp_chunking'} = 1;
264 carp 'Net::SMTP::mail: BINARYMIME option not supported by host';
267 elsif(exists $esmtp->{'8BITMIME'} or exists $esmtp->{'BINARYMIME'})
269 $opts .= " BODY=7BIT";
273 carp 'Net::SMTP::mail: 8BITMIME and BINARYMIME options not supported by host';
277 if(defined($v = delete $opt{Transaction}))
279 if(exists $esmtp->{CHECKPOINT})
281 $opts .= " TRANSID=" . _addr($me, $v);
285 carp 'Net::SMTP::mail: CHECKPOINT option not supported by host';
289 if(defined($v = delete $opt{Envelope}))
291 if(exists $esmtp->{DSN})
293 $v =~ s/([^\041-\176]|=|\+)/sprintf "+%02x", ord($1)/sge;
298 carp 'Net::SMTP::mail: DSN option not supported by host';
302 carp 'Net::SMTP::recipient: unknown option(s) '
303 . join(" ", keys %opt)
309 carp 'Net::SMTP::mail: ESMTP not supported by host - options discarded :-(';
313 $me->_MAIL("FROM:".$addr.$opts);
316 sub send { my $me = shift; $me->_SEND("FROM:" . _addr($me, $_[0])) }
317 sub send_or_mail { my $me = shift; $me->_SOML("FROM:" . _addr($me, $_[0])) }
318 sub send_and_mail { my $me = shift; $me->_SAML("FROM:" . _addr($me, $_[0])) }
325 if(exists ${*$me}{'net_smtp_lastch'});
337 if(@_ && ref($_[-1]))
339 my %opt = %{pop(@_)};
342 $skip_bad = delete $opt{'SkipBad'};
344 if(exists ${*$smtp}{'net_smtp_esmtp'})
346 my $esmtp = ${*$smtp}{'net_smtp_esmtp'};
348 if(defined($v = delete $opt{Notify}))
350 if(exists $esmtp->{DSN})
352 $opts .= " NOTIFY=" . join(",",map { uc $_ } @$v)
356 carp 'Net::SMTP::recipient: DSN option not supported by host';
360 carp 'Net::SMTP::recipient: unknown option(s) '
361 . join(" ", keys %opt)
367 carp 'Net::SMTP::recipient: ESMTP not supported by host - options discarded :-(';
375 if($smtp->_RCPT("TO:" . _addr($smtp, $addr) . $opts)) {
376 push(@ok,$addr) if $skip_bad;
383 return $skip_bad ? @ok : 1;
396 if(exists ${*$me}{'net_smtp_chunking'})
398 carp 'Net::SMTP::data: CHUNKING extension in use, must call bdat instead';
402 my $ok = $me->_DATA() && $me->datasend(@_);
404 $ok && @_ ? $me->dataend
413 if(exists ${*$me}{'net_smtp_chunking'})
417 $me->_BDAT(length $data) && $me->rawdatasend($data) &&
418 $me->response() == CMD_OK;
422 carp 'Net::SMTP::bdat: CHUNKING extension is not in use, call data instead';
430 if(exists ${*$me}{'net_smtp_chunking'})
434 $me->_BDAT(length $data, "LAST") && $me->rawdatasend($data) &&
435 $me->response() == CMD_OK;
439 carp 'Net::SMTP::bdat: CHUNKING extension is not in use, call data instead';
445 return unless $me->_DATA();
453 $me->_EXPN(@_) ? ($me->message)
458 sub verify { shift->_VRFY(@_) }
464 $me->_HELP(@_) ? scalar $me->message
485 sub _EHLO { shift->command("EHLO", @_)->response() == CMD_OK }
486 sub _HELO { shift->command("HELO", @_)->response() == CMD_OK }
487 sub _MAIL { shift->command("MAIL", @_)->response() == CMD_OK }
488 sub _RCPT { shift->command("RCPT", @_)->response() == CMD_OK }
489 sub _SEND { shift->command("SEND", @_)->response() == CMD_OK }
490 sub _SAML { shift->command("SAML", @_)->response() == CMD_OK }
491 sub _SOML { shift->command("SOML", @_)->response() == CMD_OK }
492 sub _VRFY { shift->command("VRFY", @_)->response() == CMD_OK }
493 sub _EXPN { shift->command("EXPN", @_)->response() == CMD_OK }
494 sub _HELP { shift->command("HELP", @_)->response() == CMD_OK }
495 sub _RSET { shift->command("RSET")->response() == CMD_OK }
496 sub _NOOP { shift->command("NOOP")->response() == CMD_OK }
497 sub _QUIT { shift->command("QUIT")->response() == CMD_OK }
498 sub _DATA { shift->command("DATA")->response() == CMD_MORE }
499 sub _BDAT { shift->command("BDAT", @_) }
500 sub _TURN { shift->unsupported(@_); }
501 sub _ETRN { shift->command("ETRN", @_)->response() == CMD_OK }
502 sub _AUTH { shift->command("AUTH", @_)->response() == CMD_OK }
510 Net::SMTP - Simple Mail Transfer Protocol Client
517 $smtp = Net::SMTP->new('mailhost');
518 $smtp = Net::SMTP->new('mailhost', Timeout => 60);
522 This module implements a client interface to the SMTP and ESMTP
523 protocol, enabling a perl5 application to talk to SMTP servers. This
524 documentation assumes that you are familiar with the concepts of the
525 SMTP protocol described in RFC821.
527 A new Net::SMTP object must be created with the I<new> method. Once
528 this has been done, all SMTP commands are accessed through this object.
530 The Net::SMTP class is a subclass of Net::Cmd and IO::Socket::INET.
534 This example prints the mail domain name of the SMTP server known as mailhost:
536 #!/usr/local/bin/perl -w
540 $smtp = Net::SMTP->new('mailhost');
541 print $smtp->domain,"\n";
544 This example sends a small message to the postmaster at the SMTP server
547 #!/usr/local/bin/perl -w
551 $smtp = Net::SMTP->new('mailhost');
553 $smtp->mail($ENV{USER});
554 $smtp->to('postmaster');
557 $smtp->datasend("To: postmaster\n");
558 $smtp->datasend("\n");
559 $smtp->datasend("A simple test message\n");
568 =item new Net::SMTP [ HOST, ] [ OPTIONS ]
570 This is the constructor for a new Net::SMTP object. C<HOST> is the
571 name of the remote host to which an SMTP connection is required.
573 If C<HOST> is an array reference then each value will be attempted
574 in turn until a connection is made.
576 If C<HOST> is not given, then the C<SMTP_Host> specified in C<Net::Config>
579 C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
580 Possible options are:
582 B<Hello> - SMTP requires that you identify yourself. This option
583 specifies a string to pass as your mail domain. If not
584 given a guess will be taken.
586 B<LocalAddr> and B<LocalPort> - These parameters are passed directly
587 to IO::Socket to allow binding the socket to a local port.
589 B<Timeout> - Maximum time, in seconds, to wait for a response from the
590 SMTP server (default: 120)
592 B<ExactAddresses> - If true the all ADDRESS arguments must be as
593 defined by C<addr-spec> in RFC2822. If not given, or false, then
594 Net::SMTP will attempt to extract the address from the value passed.
596 B<Debug> - Enable debugging information
602 $smtp = Net::SMTP->new('mailhost',
603 Hello => 'my.mail.domain'
612 Unless otherwise stated all methods return either a I<true> or I<false>
613 value, with I<true> meaning that the operation was a success. When a method
614 states that it returns a value, failure will be returned as I<undef> or an
621 Returns the banner message which the server replied with when the
622 initial connection was made.
626 Returns the domain that the remote SMTP server identified itself as during
629 =item hello ( DOMAIN )
631 Tell the remote server the mail domain which you are in using the EHLO
632 command (or HELO if EHLO fails). Since this method is invoked
633 automatically when the Net::SMTP object is constructed the user should
634 normally not have to call it manually.
636 =item etrn ( DOMAIN )
638 Request a queue run for the DOMAIN given.
640 =item auth ( USERNAME, PASSWORD )
642 Attempt SASL authentication.
644 =item mail ( ADDRESS [, OPTIONS] )
646 =item send ( ADDRESS )
648 =item send_or_mail ( ADDRESS )
650 =item send_and_mail ( ADDRESS )
652 Send the appropriate command to the server MAIL, SEND, SOML or SAML. C<ADDRESS>
653 is the address of the sender. This initiates the sending of a message. The
654 method C<recipient> should be called for each address that the message is to
657 The C<mail> method can some additional ESMTP OPTIONS which is passed
658 in hash like fashion, using key and value pairs. Possible options are:
661 Return => "FULL" | "HDRS"
662 Bits => "7" | "8" | "binary"
663 Transaction => <ADDRESS>
666 The C<Return> and C<Envelope> parameters are used for DSN (Delivery
667 Status Notification).
671 Reset the status of the server. This may be called after a message has been
672 initiated, but before any data has been sent, to cancel the sending of the
675 =item recipient ( ADDRESS [, ADDRESS [ ...]] [, OPTIONS ] )
677 Notify the server that the current message should be sent to all of the
678 addresses given. Each address is sent as a separate command to the server.
679 Should the sending of any address result in a failure then the
680 process is aborted and a I<false> value is returned. It is up to the
681 user to call C<reset> if they so desire.
683 The C<recipient> method can some additional OPTIONS which is passed
684 in hash like fashion, using key and value pairs. Possible options are:
687 SkipBad => ignore bad addresses
689 If C<SkipBad> is true the C<recipient> will not return an error when a
690 bad address is encountered and it will return an array of addresses
693 $smtp->recipient($recipient1,$recipient2); # Good
694 $smtp->recipient($recipient1,$recipient2, { SkipBad => 1 }); # Good
695 $smtp->recipient("$recipient,$recipient2"); # BAD
697 =item to ( ADDRESS [, ADDRESS [...]] )
699 =item cc ( ADDRESS [, ADDRESS [...]] )
701 =item bcc ( ADDRESS [, ADDRESS [...]] )
703 Synonyms for C<recipient>.
705 =item data ( [ DATA ] )
707 Initiate the sending of the data from the current message.
709 C<DATA> may be a reference to a list or a list. If specified the contents
710 of C<DATA> and a termination string C<".\r\n"> is sent to the server. And the
711 result will be true if the data was accepted.
713 If C<DATA> is not specified then the result will indicate that the server
714 wishes the data to be sent. The data must then be sent using the C<datasend>
715 and C<dataend> methods described in L<Net::Cmd>.
717 =item expand ( ADDRESS )
719 Request the server to expand the given address Returns an array
720 which contains the text read from the server.
722 =item verify ( ADDRESS )
724 Verify that C<ADDRESS> is a legitimate mailing address.
726 =item help ( [ $subject ] )
728 Request help text from the server. Returns the text or undef upon failure
732 Send the QUIT command to the remote SMTP server and close the socket connection.
738 Net::SMTP attempts to DWIM with addresses that are passed. For
739 example an application might extract The From: line from an email
740 and pass that to mail(). While this may work, it is not reccomended.
741 The application should really use a module like L<Mail::Address>
742 to extract the mail address and pass that.
744 If C<ExactAddresses> is passed to the contructor, then addresses
745 should be a valid rfc2821-quoted address, although Net::SMTP will
746 accept accept the address surrounded by angle brackets.
748 funny user@domain WRONG
749 "funny user"@domain RIGHT, recommended
750 <"funny user"@domain> OK
758 Graham Barr <gbarr@pobox.com>
762 Copyright (c) 1995-1997 Graham Barr. All rights reserved.
763 This program is free software; you can redistribute it and/or modify
764 it under the same terms as Perl itself.
768 I<$Id: //depot/libnet/Net/SMTP.pm#31 $>