Site icon Dipin Krishna

Perl: Send bulk mail via SMTP with authentication

perl

This is a tutorial on how to send mails to multiple recipients using Perl Net::SMTP module with authentication.

The smtp module implements a client interface to the SMTP and ESMTP protocol, enabling a perl5 application to talk to SMTP servers.

The first step is to create a SMTP connection to the server. A new Net::SMTP object must be created with the new method. Once this has been done, all SMTP commands are accessed through this object. The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). You can also specify the port, if you are using Google’s SMTP server ‘smtp.gmail.com’ then specify the port as 587.

my $smtp = new Net::SMTP(
  $mailhost,
  #Port    =>      587,
  Timeout  =>      10
);

Then authenticate the connection using your username and password.

$smtp->auth ( $sender, $password ) or die "Could not authenticate $!";

Now send the mail to all recipient one by one.

Below is a sample script doing this

#!/usr/bin/perl
#-------------------------------------------------#
#  File:    bulkmail.pl                           #
#  Author:  Dipin Krishna                         #
#-------------------------------------------------#
 
#########-- Enter the Details here --###################################
 
$mailhost           = 'mail.test.com';
$sender             = 'sender@test.com';
$sender_name        = 'Sender Name';
$password           = 'Password';
$subject            = 'Test';
$body               = 'This is a test';
$recipientlistfile  = 'filename.txt';
 
########################################################################
use Net::SMTP;
 
sub trim($)
{
  my $string = shift;
  $string =~ s/^\s+//;
  $string =~ s/\s+$//;
  return $string;
}
 
open FILE, "<$recipientlistfile" or die $!;
 
my $smtp = new Net::SMTP(
  $mailhost,
  #Port    =>      587,
  #Timeout =>      10
);
$smtp->auth ( $sender, $password ) or die "Could not authenticate $!";
 
while (<FILE>) {
  $reciever = $_;
  $reciever = trim($reciever);
  print "sending to $reciever\n";
 
#  -- Enter sender mail address. --
  $smtp->mail($sender);
 
#  -- Enter recipient mails address. --
  $smtp->recipient($reciever);
 
  $smtp->data();
 
# -- This part creates the SMTP headers you see. --
  $smtp->datasend("To: <$reciever> \n");
  $smtp->datasend("From: $sender_name <$sender> \n");
  $smtp->datasend("Content-Type: text/html \n");
  $smtp->datasend("Subject: $subject");
 
# -- line break to separate headers from message body. --
  $smtp->datasend("\n");
 
  $smtp->datasend($body);
 
  $smtp->datasend("\n");
  $smtp->dataend();
 
}
$smtp->quit;
close(FILE);
Exit mobile version