Site icon Dipin Krishna

Perl: Send an E-Mail using Email::Simple and Email::Sender

perl

Email::Simple is the first deliverable of the “Perl Email Project.” The Email:: namespace was begun as a reaction against the increasing complexity and bugginess of Perl’s existing email modules. Email::* modules are meant to be simple to use and to maintain, pared to the bone, fast, minimal in their external dependencies, and correct.

Email::Sender replaces the old and sometimes problematic Email::Send library, which did a decent job at handling very simple email sending tasks, but was not suitable for serious use, for a variety of reasons. Most users will be able to use Email::Sender::Simple to send mail. Users with more specific needs should look at the available Email::Sender::Transport classes. Documentation may be found in Email::Sender::Manual, and new users should start with Email::Sender::Manual::QuickStart.

We will create a email message object using Email::Simple and use the sub sendmail in Email::Sender::Simple. We are using Email::Sender::Transport::SMTP to send the mail over SMTP.

  1.  use strict;
  2.  use warnings;
  3.  use Try::Tiny;
  4.  
  5.  use Email::Simple;
  6.  use Email::Sender::Simple qw(sendmail);
  7.  use Email::Sender::Transport::SMTP::TLS;
  8.  
  9.  # Create the email message object.
  10.  my $email_object = Email::Simple->create(
  11.      header => [
  12.          From           => 'USERNAME@gmail.com',
  13.          To             => 'RECEIVER@gmail.com',
  14.          Subject        => 'TEST MAIL!',
  15.      ],
  16.      body => 'THIS IS A TEST EMAIL',
  17.  );
  18.  
  19.  # Create the transport. Using gmail for this example
  20.  my $transport = Email::Sender::Transport::SMTP::TLS->new(
  21.      host     => 'smtp.gmail.com',
  22.      port     => 587,
  23.      username => 'USERNAME@gmail.com',
  24.      password => 'PASSWORD'
  25.  );
  26.  
  27.  # send the mail
  28.  try {
  29.         sendmail( $email_object, {transport => $transport} );
  30.  } catch {
  31.         warn "Email sending failed: $_";
  32.  };

Hope, it helps! 🙂

Exit mobile version