Scripting‎ > ‎Perl examples‎ > ‎

send email in perl

Thank you for visiting this page, this page has been update in another link Send e-mail in perl
Want to send e-mail in perl, here is my example:

This example calls linux system command sendmail

sub sendmail {
  my $msg = $_[0];
  my $mailtype= $_[1];
  my $mailsubject= $_[2];

  my $mailtarget;

  $msg =~ /^(([[:print:]\s])+)$/;
  $msg = $1;
  $msg =~ s/[|]|[;]|[!]/ /g;
  if($mailtype == _MAIL ) {
    $mailtarget = 'abcd@abcd.com';
  }
  else {
    $mailtarget = '1234@1234.comt';
  }
  my $sm = "/usr/sbin/sendmail -t";
  open( SENDMAIL, "|$sm" ) or die( "Cannot open $sm: $!" );
  print SENDMAIL "From: $mailtarget\n";
  print SENDMAIL "Reply-to: $mailtarget\n";
  print SENDMAIL "To: $mailtarget\n";
  print SENDMAIL "Subject: ".$mailsubject."\n";
  print SENDMAIL "Content-type: text/plain\n\n";
  print SENDMAIL "Dear System Adminstrator:\n\nThe following traps have been received from devices since last time report:\n\n";
  print SENDMAIL "$msg\n";
  close( SENDMAIL );
}


Another way is to use perl mail module
use Mail::Sendmail; sendmail( From => 'sender@somewhereelse.com', To => 'recipient@somewhere.com', Subject => 'some subject', Message => "body of the message", );
Or, use sendmail module to customize MIME::Lite , send an mail with attachment.
sub sendmail
{
  my $msg_body = $_[0];
  my $from_address= $_[1];
  my $tomail= $_[2];
  my $subject=$_[3];
  my $tempfile=$_[4];
  my $sender = new Mail::Sender({
        from => $from_address,
    });
    $sender->OpenMultipart({
        to => $tomail,
        subject => $subject,
    });
    $sender->Body;
    $sender->SendLine( $msg_body );
    $sender->SendFile({
        description => 'Raw Data File',
        encoding => '7BIT',
        file => $tempfile,
    });
    $sender->Close;
}

You can do more complex things with perl Mail::Sendmail module, but most of time, sending message is the most important part for system admin, particularly in scripting. 

Here is  more for you, the following function is for admins to decide to do logging or to call sendmail

sub logMsg
{
  my $msg = $_[0];
  my $exit = $_[1];
  my $subject = $_[2];
  my $time = strftime( "%b %d %H:%M:%S", localtime() );
  printf( "%s %s\n", $time, $msg );
  if( $exit ) {
    if($exit == _DIE  ) {
      sendmail( "$msg", $exit,"exiting: $msg" );
      exit( $exit );
    }
    if($exit == _MAIL ) {
      printf( "%s sendding mail \n", $time );
      sendmail( "$msg", $exit,"$subject");
    }
    else {
      printf( "%s Hey guess this is goodbye.. would send mail\n", $time );
      exit( $exit );
    }
  }
}




Comments