22 de junio de 2016

email desde servidor TLS con perl

Hola,
en la entrada de hoy muestro una manera de enviar correo electrónico desde un servidor seguro (STARTTLS) por medio de un script Perl. Hasta hace poco lo hacía con el vetusto módulo Net::SMTP::TLS, pero esta solución era muy frágil y se rompía cada vez que otros módulos (fundamentalmente IO::Socket::SSL) no iban a la par en sus versiones. De hecho, en un sistema Ubuntu 14 no he logrado hacerla funcionar actualizando esos módulos, pero cambio he descubierto que con el módulo Net::SMTPS es más sencillo. Aquí queda el código:

 use strict;  
 use MIME::Lite;  
 use Net::SMTPS;  
   
 my $HELLOIP   = 'xxx.xxx.xxx.xxx'; # your IP, must be allowed by $SECURESERVER  
 my $SECURESERVER = 'smtp.domain.com'; # can also be an IP address  
 my $SECUREPORT  = 587;  
 my $SECUREUSER  = 'secure_user';   # user login in secure server  
 my $SECUREPASSWD = 'zzzzzzzzzzz';   # user password, better read from safe file  
 my $SECURESENDER = 'user@domain.com'; # must be owned by $SECUREUSER  
     
 send_email(   
  $HELLOIP,$SECURESERVER,$SECUREPORT,  
  $SECUREUSER,$SECUREPASSWD,  
  $SECURESENDER,'recipient@test.domain.org',   
  'probando','texto de prueba'  
  );  
   
 sub send_email  
 {  
  my ($hello,$host,$port,$user,$pass,$sender,$recipient,$subject,$text) = @_;  
   
  # connect to server  
  my $smtp = new Net::SMTPS(  
   $host,  
   Hello  =>$hello,  
   Port  =>$port,  
   doSSL  =>'starttls',  
   Debug  =>0 # change to 1 to see behind the curtains  
  );  
   
  $smtp->auth($user,$pass); # login  
   
  # Create the multipart container  
  my $msg = MIME::Lite->new (  
   From  => $sender,  
   To   => $recipient,  
   Subject => $subject,  
   Type  =>'multipart/mixed'  
  ) or die "# send_email : error creating multipart container: $!\n";  
   
  # add main-text if required  
  if($text)  
  {  
   $msg->attach (  
    Type => 'text/plain',  
    Data => $text  
   ) or die "# send_email : error adding the text message part: $!\n";  
  }   
   
  # actually send email  
  $smtp->mail($sender);  
     
  if($smtp->to($recipient))  
  {   
   $smtp -> data();  
   $smtp -> datasend( $msg->as_string() );   
   $smtp -> dataend();  
  }  
  else{ print "# ERROR: ". $smtp->message() }   
   
    $smtp->quit();  
 }  
   
   

Hasta la próxima,
Bruno


1 comentario: