Unix Tip: Sending HTML email

By , ITworld |  Small Business, email, Sandra Henry-Stocker

A common task of sysadmins is to generate email messages and send them out to a group of people. Reminders about upcoming system downtime or tips to help users make better use of their Unix accounts might be sent out routinely. In this week's column, we look at a bare bones script for sending out email in HTML format.

First, we'll start off our script with a typical Perl shebang line, assign the location of the sendmail executable to $sendmail and the sender's email address to $sender.

#!/usr/bin/perl -w



my $sendmail = "/usr/lib/sendmail";

my $sender = "jdoe\@boson.net";

Next, we'll verify that the user has supplied a single argument (in this case, the email address of the intended recipient) on the command line:

if ( $#ARGV != 0 ) {
    print "Usage: $0 <recipient>n";
    print "$ARGV[0]\n";
    exit;
}

If the user has not used the correct command format when invoking the script, we issue a usage statement and then exit. Otherwise, we accept the argument provided and assign it to $email:

$email = $ARGV[0];

The next step is opening a pipe to the sendmail program. This is done easily with the open command:

# Open a pipe to the sendmail program

open(OUT, "|$sendmail -t");

We then come to the point at which we need to format the email we are sending in HTML. This requires that we create a MIME header to tell the mail client how the message should be processed:

print OUT <<EOM

Mime-Version: 1.0

Content-type: text/html; charset="iso-8859-1"

Now that we've paved the way for our email to be in HTML format, we can add our From, To and Subject lines. In a multi-purpose script, you would probably pass the subject line as a second argument or maybe read it from a file along with other information about the message you are sending.

From: $sender

To: $email

Subject: Your tasks for the upcoming party

Now comes the content of the message. Since we are sending HTML email, we will start with the <html> and <body> tags:

<html>

<body>

At this point, you could insert your message text into the script, add the </body> and </html> tags and be done with it. But, since we are sending out HTML, we might as well take advantage of HTML to format our message. In lines text below, we have created a list of tasks that volunteers have agreed to help with at an upcoming picnic. The checked items are those for which this particular recipient has volunteered. Notice that we're using HTML form commands to create the check list. This will end up looking fairly nice in the recipient's inbox. The recipient will both see a list of the tasks for which volunteers are needed and will see his own tasks checked off.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

ITworld Answers helps you solve problems and share expertise. Ask a question or take a crack at answering the new questions below.

Ask a Question