How to Use Perl to Send HTML Email

Sending a plain text email from a Perl script can be done in a straightforward manner. The process becomes more involved when you need to send an HTML formatted email. You can't just send an HTML formatted message. You need to tell your email server that you are, in fact, sending an HTML email. Using an SMTP server with authentication (as most new users will be doing) also adds an extra layer of complexity. Fortunately, Perl provides packages that do all the hard work for you.

Instructions

    • 1

      Install MIME::Lite::TT::HTML and Net::SMTP::SSL. In Linux, use CPAN. In Windows, use the Perl Package Manager.

    • 2

      Create the HTML email using the editor of your choice. Use a dedicated HTML editor or a Word processor that can save documents as HTML files. Name the file "email.html" and write down the location of the file.

    • 3

      Copy the following code into an empty file of your choice. The script uses MIME::Lite::TT::HTML to create an HTML email and Net::SMTP::SSL to send the email using your SMTP server.

      #!/usr/bin/perl
      use warnings;
      use strict;
      use MIME::Lite::TT::HTML;
      use Net::SMTP::SSL;

      my $smtp_server='smtp.server.address';
      my $username='your.username';
      my $password='your.password';
      my $port=465;
      my $path_to_files='path to location of email.html';
      my $from='from.address';
      my $to='to.address';
      my $subject='Subject line';

      my $smtp = Net::SMTP::SSL->new( $smtp_server, Port=>$port );
      $smtp -> auth( $username, $password );

      my %params;
      my %options;
      $options{INCLUDE_PATH} = $path_to_files;

      my $msg = MIME::Lite::TT::HTML->new(
      From => $from,
      To => $to,
      Subject => $subject,
      Template => {
      html => 'email.html',
      },
      TmplOptions => \%options,
      TmplParams => \%params,
      );

      $smtp->mail($from);
      $smtp->to($to);
      $smtp -> data();
      $smtp -> datasend( $msg->as_string() );
      $smtp -> dataend();
      $smtp -> quit;

    • 4

      Customize the file using your settings. You will need to set the following variables for your SMTP server: "smtp_server," "username," "password" and "port." The "path_to_files" variable is the location of the HTML email from Step 2. The "from," "to" and "subject" variables are the usual email settings.

    • 5

      Run the script. In Linux, you will first need to give the script execute permissions.

Tips & Warnings

  • This file stores your email password in plain text, so anyone with access to the file will know your password. Be careful not to save this file on a public computer.

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured