Sending an email from command line by a Perl script
With the ability to send emails in the command line, we can imagine that some more practical tasks become feasible:
- Hooking it up to CGI applications or cron to send status reports, alerts, etc.
- Composing dynamically formatted emails and sending them to a large number of people in a sending list.
But, of course, please don't be a spammer!! In this article, I introduce a very simple way to compose and send an email using Perl with the help of an excellent command-line email client program. After learning it, you should be able to extend it to do much more practical tasks.
For an example of how to scale this method to deal with a large number of emails, see the sequel to this article.
Prerequisites
To send emails from your computer, you should have a properly configured MTA (Mail Transfer Agent). The default MTA for Ubuntu is Postfix. Before proceeding to the following part of this article, please set up Postfix on your computer. When I set up Postfix myself, I followed this Ubuntu community document.
Method
To construct an email, we need an email client program. In this article, we use sendEmail, a Perl script program with many practical options to construct and send out emails. To install sendEmail on your Ubuntu system, do
$ sudo apt-get install sendemail
Since sendEmail is a Perl script, we can directly call it from the shell prompt to send out an email.
$ sendEmail -t 'Mr.X <company@example.com>' \
-f 'Taro Yamada <taro@example.net>' \
-u 'English Title' \
-m 'Hello there!!' \
-s localhost:25
This will send an email to company@example.com with subject "English Title" and message "Hello there!!" with from field filled as taro@example.net. Pretty cool!
However, typing all the fields and messages directly into the command line is not always convenient. To make it more useful and extendable, let's create a Perl script that calls sendEmail internally as:
#!/usr/bin/perl
$to = 'Mr.X <company@example.com>';
$from = 'Taro Yamada <taro@example.net>';
$subject = 'English Title';
$file_body = './body-english.txt';
$cmd = "sendEmail " .
"-f \"$from\" " .
"-t \"$to\" " .
"-u \"$subject\" " .
"-o message-file=$file_body " .
"-s localhost:25" .
"\n";
print $cmd;
system("$cmd");
,where the message body is read from a plain text file
Dear Mr.X, This is a mock email body text to show how to send an email by Perl. Sincerely, Taro Yamada
To execute send-email-en.pl, make it executable with chmod and run it from the current directory:
$ chmod 775 send-email-en.pl $ ./send-email-en.pl
In this way, we obtain the flexibility to modify each email-related field under the Perl's very powerful text-manipulation framework. The number of its applications is limitless!