home *** CD-ROM | disk | FTP | other *** search
/ CLIX - Fazer Clix Custa Nix / CLIX-CD.cdr / mac / lib / Net / SMTP.pm < prev    next >
Text File  |  1997-11-18  |  12KB  |  543 lines

  1. # Net::SMTP.pm
  2. #
  3. # Copyright (c) 1995-1997 Graham Barr <gbarr@ti.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.
  6.  
  7. package Net::SMTP;
  8.  
  9. require 5.001;
  10.  
  11. use strict;
  12. use vars qw($VERSION @ISA);
  13. use Socket 1.3;
  14. use Carp;
  15. use IO::Socket;
  16. use Net::Cmd;
  17. use Net::Config;
  18.  
  19. $VERSION = do { my @r=(q$Revision: 1.1 $=~/\d+/g); sprintf "%d."."%02d"x$#r,@r};
  20.  
  21. @ISA = qw(Net::Cmd IO::Socket::INET);
  22.  
  23. sub new
  24. {
  25.  my $self = shift;
  26.  my $type = ref($self) || $self;
  27.  my $host = shift if @_ % 2;
  28.  my %arg  = @_; 
  29.  my $hosts = defined $host ? [ $host ] : $NetConfig{smtp_hosts};
  30.  my $obj;
  31.  
  32.  my $h;
  33.  foreach $h (@{$hosts})
  34.   {
  35.    $obj = $type->SUPER::new(PeerAddr => ($host = $h), 
  36.                 PeerPort => $arg{Port} || 'smtp(25)',
  37.                 Proto    => 'tcp',
  38.                 Timeout  => defined $arg{Timeout}
  39.                         ? $arg{Timeout}
  40.                         : 120
  41.                ) and last;
  42.   }
  43.  
  44.  return undef
  45.     unless defined $obj;
  46.  
  47.  $obj->autoflush(1);
  48.  
  49.  $obj->debug(exists $arg{Debug} ? $arg{Debug} : undef);
  50.  
  51.  unless ($obj->response() == CMD_OK)
  52.   {
  53.    $obj->SUPER::close();
  54.    return undef;
  55.   }
  56.  
  57.  ${*$obj}{'net_smtp_host'} = $host;
  58.  
  59.  (${*$obj}{'net_smtp_domain'}) = $obj->message =~ /\A\s*(\S+)/;
  60.  
  61.  $obj->hello($arg{Hello} || "");
  62.  
  63.  $obj;
  64. }
  65.  
  66. ##
  67. ## User interface methods
  68. ##
  69.  
  70. sub domain
  71. {
  72.  my $me = shift;
  73.  
  74.  return ${*$me}{'net_smtp_domain'} || undef;
  75. }
  76.  
  77. sub hello
  78. {
  79.  my $me = shift;
  80.  my $domain = shift ||
  81.           eval {
  82.             require Net::Domain;
  83.             Net::Domain::hostfqdn();
  84.            } ||
  85.         "";
  86.  my $ok = $me->_EHLO($domain);
  87.  my $msg;
  88.  
  89.  if($ok)
  90.   {
  91.    $msg = $me->message;
  92.  
  93.    my $h = ${*$me}{'net_smtp_esmtp'} = {};
  94.    my $ext;
  95.    foreach $ext (qw(8BITMIME CHECKPOINT DSN SIZE))
  96.     {
  97.      $h->{$ext} = 1
  98.     if $msg =~ /\b${ext}\b/;
  99.     }
  100.   }
  101.  else
  102.   {
  103.    $msg = $me->message
  104.     if $me->_HELO($domain);
  105.   }
  106.  
  107.  $ok && $msg =~ /\A(\S+)/
  108.     ? $1
  109.     : undef;
  110. }
  111.  
  112. sub _addr
  113. {
  114.  my $addr = shift || "";
  115.  
  116.  return $1
  117.     if $addr =~ /(<[^>]+>)/so;
  118.  
  119.  $addr =~ s/\n/ /sog;
  120.  $addr =~ s/(\A\s+|\s+\Z)//sog;
  121.  
  122.  return "<" . $addr . ">";
  123. }
  124.  
  125.  
  126. sub mail
  127. {
  128.  my $me = shift;
  129.  my $addr = _addr(shift);
  130.  my $opts = "";
  131.  
  132.  if(@_)
  133.   {
  134.    my %opt = @_;
  135.    my($k,$v);
  136.  
  137.    if(exists ${*$me}{'net_smtp_esmtp'})
  138.     {
  139.      my $esmtp = ${*$me}{'net_smtp_esmtp'};
  140.  
  141.      if(defined($v = delete $opt{Size}))
  142.       {
  143.        if(exists $esmtp->{SIZE})
  144.         {
  145.          $opts .= sprintf " SIZE=%d", $v + 0
  146.         }
  147.        else
  148.         {
  149.      carp 'Net::SMTP::mail: SIZE option not supported by host';
  150.         }
  151.       }
  152.  
  153.      if(defined($v = delete $opt{Return}))
  154.       {
  155.        if(exists $esmtp->{DSN})
  156.         {
  157.      $opts .= " RET=" . uc $v
  158.         }
  159.        else
  160.         {
  161.      carp 'Net::SMTP::mail: DSN option not supported by host';
  162.         }
  163.       }
  164.  
  165.      if(defined($v = delete $opt{Bits}))
  166.       {
  167.        if(exists $esmtp->{'8BITMIME'})
  168.         {
  169.      $opts .= $v == 8 ? " BODY=8BITMIME" : " BODY=7BIT"
  170.         }
  171.        else
  172.         {
  173.      carp 'Net::SMTP::mail: 8BITMIME option not supported by host';
  174.         }
  175.       }
  176.  
  177.      if(defined($v = delete $opt{Transaction}))
  178.       {
  179.        if(exists $esmtp->{CHECKPOINT})
  180.         {
  181.      $opts .= " TRANSID=" . _addr($v);
  182.         }
  183.        else
  184.         {
  185.      carp 'Net::SMTP::mail: CHECKPOINT option not supported by host';
  186.         }
  187.       }
  188.  
  189.      if(defined($v = delete $opt{Envelope}))
  190.       {
  191.        if(exists $esmtp->{DSN})
  192.         {
  193.      $v =~ s/([^\041-\176]|=|\+)/sprintf "+%02x", ord($1)/sge;
  194.      $opts .= " ENVID=$v"
  195.         }
  196.        else
  197.         {
  198.      carp 'Net::SMTP::mail: DSN option not supported by host';
  199.         }
  200.       }
  201.  
  202.      carp 'Net::SMTP::recipient: unknown option(s) '
  203.         . join(" ", keys %opt)
  204.         . ' - ignored'
  205.     if scalar keys %opt;
  206.     }
  207.    else
  208.     {
  209.      carp 'Net::SMTP::mail: ESMTP not supported by host - options discarded :-(';
  210.     }
  211.   }
  212.  
  213.  $me->_MAIL("FROM:".$addr.$opts);
  214. }
  215.  
  216. sub send      { shift->_SEND("FROM:" . _addr($_[0])) }
  217. sub send_or_mail  { shift->_SOML("FROM:" . _addr($_[0])) }
  218. sub send_and_mail { shift->_SAML("FROM:" . _addr($_[0])) }
  219.  
  220. sub reset
  221. {
  222.  my $me = shift;
  223.  
  224.  $me->dataend()
  225.     if(exists ${*$me}{'net_smtp_lastch'});
  226.  
  227.  $me->_RSET();
  228. }
  229.  
  230.  
  231. sub recipient
  232. {
  233.  my $smtp = shift;
  234.  my $ok = 1;
  235.  my $opts = "";
  236.  
  237.  if(@_ && ref($_[-1]))
  238.   {
  239.    my %opt = %{pop(@_)};
  240.    my $v;
  241.  
  242.    if(exists ${*$smtp}{'net_smtp_esmtp'})
  243.     {
  244.      my $esmtp = ${*$smtp}{'net_smtp_esmtp'};
  245.  
  246.      if(defined($v = delete $opt{Notify}))
  247.       {
  248.        if(exists $esmtp->{DSN})
  249.         {
  250.      $opts .= " NOTIFY=" . join(",",map { uc $_ } @$v)
  251.         }
  252.        else
  253.         {
  254.      carp 'Net::SMTP::recipient: DSN option not supported by host';
  255.         }
  256.       }
  257.  
  258.      carp 'Net::SMTP::recipient: unknown option(s) '
  259.         . join(" ", keys %opt)
  260.         . ' - ignored'
  261.     if scalar keys %opt;
  262.     }
  263.    else
  264.     {
  265.      carp 'Net::SMTP::recipient: ESMTP not supported by host - options discarded :-(';
  266.     }
  267.   }
  268.  
  269.  while($ok && scalar(@_))
  270.   {
  271.    $ok = $smtp->_RCPT("TO:" . _addr(shift) . $opts);
  272.   }
  273.  
  274.  return $ok;
  275. }
  276.  
  277. sub to { shift->recipient(@_) }
  278.  
  279. sub data
  280. {
  281.  my $me = shift;
  282.  
  283.  my $ok = $me->_DATA() && $me->datasend(@_);
  284.  
  285.  $ok && @_ ? $me->dataend
  286.        : $ok;
  287. }
  288.  
  289. sub expand
  290. {
  291.  my $me = shift;
  292.  
  293.  $me->_EXPN(@_) ? ($me->message)
  294.         : ();
  295. }
  296.  
  297.  
  298. sub verify { shift->_VRFY(@_) }
  299.  
  300. sub help
  301. {
  302.  my $me = shift;
  303.  
  304.  $me->_HELP(@_) ? scalar $me->message
  305.             : undef;
  306. }
  307.  
  308. sub close
  309. {
  310.  my $me = shift;
  311.  
  312.  return 1
  313.    unless (ref($me) && defined fileno($me));
  314.  
  315.  $me->_QUIT && $me->SUPER::close;
  316. }
  317.  
  318. sub DESTROY { shift->close }
  319. sub quit    { shift->close }
  320.  
  321. ##
  322. ## RFC821 commands
  323. ##
  324.  
  325. sub _EHLO { shift->command("EHLO", @_)->response()  == CMD_OK }   
  326. sub _HELO { shift->command("HELO", @_)->response()  == CMD_OK }   
  327. sub _MAIL { shift->command("MAIL", @_)->response()  == CMD_OK }   
  328. sub _RCPT { shift->command("RCPT", @_)->response()  == CMD_OK }   
  329. sub _SEND { shift->command("SEND", @_)->response()  == CMD_OK }   
  330. sub _SAML { shift->command("SAML", @_)->response()  == CMD_OK }   
  331. sub _SOML { shift->command("SOML", @_)->response()  == CMD_OK }   
  332. sub _VRFY { shift->command("VRFY", @_)->response()  == CMD_OK }   
  333. sub _EXPN { shift->command("EXPN", @_)->response()  == CMD_OK }   
  334. sub _HELP { shift->command("HELP", @_)->response()  == CMD_OK }   
  335. sub _RSET { shift->command("RSET")->response()        == CMD_OK }   
  336. sub _NOOP { shift->command("NOOP")->response()        == CMD_OK }   
  337. sub _QUIT { shift->command("QUIT")->response()        == CMD_OK }   
  338. sub _DATA { shift->command("DATA")->response()        == CMD_MORE } 
  339. sub _TURN { shift->unsupported(@_); }                      
  340.  
  341. 1;
  342.  
  343. __END__
  344.  
  345. =head1 NAME
  346.  
  347. Net::SMTP - Simple Mail Transfer Protocol Client
  348.  
  349. =head1 SYNOPSIS
  350.  
  351.     use Net::SMTP;
  352.     
  353.     # Constructors
  354.     $smtp = Net::SMTP->new('mailhost');
  355.     $smtp = Net::SMTP->new('mailhost', Timeout => 60);
  356.  
  357. =head1 DESCRIPTION
  358.  
  359. This module implements a client interface to the SMTP and ESMTP
  360. protocol, enabling a perl5 application to talk to SMTP servers. This
  361. documentation assumes that you are familiar with the concepts of the
  362. SMTP protocol described in RFC821.
  363.  
  364. A new Net::SMTP object must be created with the I<new> method. Once
  365. this has been done, all SMTP commands are accessed through this object.
  366.  
  367. The Net::SMTP class is a subclass of Net::Cmd and IO::Socket::INET.
  368.  
  369. =head1 EXAMPLES
  370.  
  371. This example prints the mail domain name of the SMTP server known as mailhost:
  372.  
  373.     #!/usr/local/bin/perl -w
  374.     
  375.     use Net::SMTP;
  376.     
  377.     $smtp = Net::SMTP->new('mailhost');
  378.     print $smtp->domain,"\n";
  379.     $smtp->quit;
  380.  
  381. This example sends a small message to the postmaster at the SMTP server
  382. known as mailhost:
  383.  
  384.     #!/usr/local/bin/perl -w
  385.     
  386.     use Net::SMTP;
  387.     
  388.     $smtp = Net::SMTP->new('mailhost');
  389.     
  390.     $smtp->mail($ENV{USER});
  391.     $smtp->to('postmaster');
  392.     
  393.     $smtp->data();
  394.     $smtp->datasend("To: postmaster\n");
  395.     $smtp->datasend("\n");
  396.     $smtp->datasend("A simple test message\n");
  397.     $smtp->dataend();
  398.     
  399.     $smtp->quit;
  400.  
  401. =head1 CONSTRUCTOR
  402.  
  403. =over 4
  404.  
  405. =item new Net::SMTP [ HOST, ] [ OPTIONS ]
  406.  
  407. This is the constructor for a new Net::SMTP object. C<HOST> is the
  408. name of the remote host to which a SMTP connection is required.
  409.  
  410. If C<HOST> is not given, then the C<SMTP_Host> specified in C<Net::Config>
  411. will be used.
  412.  
  413. C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
  414. Possible options are:
  415.  
  416. B<Hello> - SMTP requires that you identify yourself. This option
  417. specifies a string to pass as your mail domain. If not
  418. given a guess will be taken.
  419.  
  420. B<Timeout> - Maximum time, in seconds, to wait for a response from the
  421. SMTP server (default: 120)
  422.  
  423. B<Debug> - Enable debugging information
  424.  
  425.  
  426. Example:
  427.  
  428.  
  429.     $smtp = Net::SMTP->new('mailhost',
  430.                Hello => 'my.mail.domain'
  431.                Timeout => 30,
  432.                            Debug   => 1,
  433.               );
  434.  
  435. =head1 METHODS
  436.  
  437. Unless otherwise stated all methods return either a I<true> or I<false>
  438. value, with I<true> meaning that the operation was a success. When a method
  439. states that it returns a value, failure will be returned as I<undef> or an
  440. empty list.
  441.  
  442. =over 4
  443.  
  444. =item domain ()
  445.  
  446. Returns the domain that the remote SMTP server identified itself as during
  447. connection.
  448.  
  449. =item hello ( DOMAIN )
  450.  
  451. Tell the remote server the mail domain which you are in using the EHLO
  452. command (or HELO if EHLO fails).  Since this method is invoked
  453. automatically when the Net::SMTP object is constructed the user should
  454. normally not have to call it manually.
  455.  
  456. =item mail ( ADDRESS [, OPTIONS] )
  457.  
  458. =item send ( ADDRESS )
  459.  
  460. =item send_or_mail ( ADDRESS )
  461.  
  462. =item send_and_mail ( ADDRESS )
  463.  
  464. Send the appropriate command to the server MAIL, SEND, SOML or SAML. C<ADDRESS>
  465. is the address of the sender. This initiates the sending of a message. The
  466. method C<recipient> should be called for each address that the message is to
  467. be sent to.
  468.  
  469. The C<mail> method can some additional ESMTP OPTIONS which is passed
  470. in hash like fashion, using key and value pairs.  Possible options are:
  471.  
  472.  Size        => <bytes>
  473.  Return      => <???>
  474.  Bits        => "7" | "8"
  475.  Transaction => <ADDRESS>
  476.  Envelope    => <ENVID>
  477.  
  478.  
  479. =item reset ()
  480.  
  481. Reset the status of the server. This may be called after a message has been 
  482. initiated, but before any data has been sent, to cancel the sending of the
  483. message.
  484.  
  485. =item recipient ( ADDRESS [, ADDRESS [ ...]] )
  486.  
  487. Notify the server that the current message should be sent to all of the
  488. addresses given. Each address is sent as a separate command to the server.
  489. Should the sending of any address result in a failure then the
  490. process is aborted and a I<false> value is returned. It is up to the
  491. user to call C<reset> if they so desire.
  492.  
  493. =item to ( ADDRESS [, ADDRESS [...]] )
  494.  
  495. A synonym for C<recipient>.
  496.  
  497. =item data ( [ DATA ] )
  498.  
  499. Initiate the sending of the data from the current message. 
  500.  
  501. C<DATA> may be a reference to a list or a list. If specified the contents
  502. of C<DATA> and a termination string C<".\r\n"> is sent to the server. And the
  503. result will be true if the data was accepted.
  504.  
  505. If C<DATA> is not specified then the result will indicate that the server
  506. wishes the data to be sent. The data must then be sent using the C<datasend>
  507. and C<dataend> methods described in L<Net::Cmd>.
  508.  
  509. =item expand ( ADDRESS )
  510.  
  511. Request the server to expand the given address Returns a reference to an array
  512. which contains the text read from the server.
  513.  
  514. =item verify ( ADDRESS )
  515.  
  516. Verify that C<ADDRESS> is a legitimate mailing address.
  517.  
  518. =item help ( [ $subject ] )
  519.  
  520. Request help text from the server. Returns the text or undef upon failure
  521.  
  522. =item quit ()
  523.  
  524. Send the QUIT command to the remote SMTP server and close the socket connection.
  525.  
  526. =back
  527.  
  528. =head1 SEE ALSO
  529.  
  530. L<Net::Cmd>
  531.  
  532. =head1 AUTHOR
  533.  
  534. Graham Barr <gbarr@ti.com>
  535.  
  536. =head1 COPYRIGHT
  537.  
  538. Copyright (c) 1995-1997 Graham Barr. All rights reserved.
  539. This program is free software; you can redistribute it and/or modify
  540. it under the same terms as Perl itself.
  541.  
  542. =cut
  543.