Bootstrap FreeKB - Perl (Scripting) - Send email using Email::Sender and Email::MIME
Perl (Scripting) - Send email using Email::Sender and Email::MIME

Updated:   |  Perl (Scripting) articles

The Email::Sender and Email::MIME modules can be installed using cpan or cpanm.

cpanm Email::Sender
cpanm Email::MIME

 

In this example, the email will be sent from john.doe@example.com to jane.doe@example.com with message body "Hello World".

#!/usr/bin/perl
use Email::Sender;
use Email::Sender::Simple qw(sendmail);
use Email::Sender::Transport::SMTP;
use Email::MIME;
use strict;
use warning;

my $from      = "john.doe\@example.com";
my $to        = "jane.doe\@example.com";
my $message   = Email::MIME->create(
  header_str => [
    From => $from,
    To => $to,
    Subject => "Greetings",
  ],
  body => "Hello World"
);
my $transport = Email::Sender::Transport::SMTP->new({
  host => 'smtp.example.com',
  port => '25'
});

sendmail($message,{transport => $transport});

 

Additionally, the Try::Tiny module can be installed so that you can use a try and catch block to determine if the email was successfully sent or if there was some problem sending the email.

cpanm Try::Tiny

 

Here is how you could include the try and catch blocks.

#!/usr/bin/perl
use Email::Sender;
use Email::Sender::Simple qw(sendmail);
use Email::Sender::Transport::SMTP;
use Email::MIME;
use strict;
use warning;

my $from      = "john.doe\@example.com";
my $to        = "jane.doe\@example.com";
my $message   = Email::MIME->create(
  header_str => [
    From => $from,
    To => $to,
    Subject => "Greetings",
  ],
  body => "Hello World"
);
my $transport = Email::Sender::Transport::SMTP->new({
  host => 'smtp.example.com',
  port => '25'
});

try {
  sendmail($message,{transport => $transport});
  print "Email successfully sent \n";
}
catch {
  print "Email sending failed \n";
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 388302 in the box below so that we can be sure you are a human.