Before we can generate reports, it is necessary to find out how to send e-mail from within a Perl program. There are, as one might expect, many ways to do this, ranging from opening a pipe to sendmail to more complex, fully featured systems; the solution presented here is toward the lower end of the complexity scale but can perform most e-mail tasks quickly and securely.
MIME::Lite is a simple, stand-alone module for generating and sending MIME e-mail messages. MIME is the mail protocol you need for mailing HTML or graphics, or anything other than just ASCII plaintext. It does not deal with message parsing (an entirely separate task), nor does it require any other modules apart from those already installed in the base Perl distribution. But it does automatically handle any necessary encoding.
The only problem occurs on Windows-based systems or on those that do not have their own mail servers; MIME::Lite uses a pipe to sendmail as its default means of getting mail off the systems. Very few Windows systems have this available. The usual approach in this case is to specify an external SMTP server. To make MIME::Lite use this function, just add:
(replacing ’hostname’ with the name of the external server, of course) to the beginning of each script that will send mail. Alternatively, if there is a program on the system that acts similarly to sendmail, set:
The preceding line is not used in the examples in this chapter.
The cron program covers the “automatic” part of this chapter’s title. This is a standard Unix function that causes a program to be run at specified times. Often, the reporting program runs under the same user id as the Web server; this might be Apache, www-data, or nobody. For this example, we use www-data.
You need shell access to set up the crontab listing for the report program, either as root or as the www-data user. Run the command:
crontab -u www-data -e
to edit the listing of tasks to be carried out automatically by the www-data user; add the new line at the end.
The format of the crontab entries can be a bit tricky, see the manual page for crontab(5) for detailed information about the format of the crontab file. The most common cases, though, are a program to be run once a day, once a week, or once a month. This can be executed by the following entries:
15 8 * * * /path/to/daily/program_name 15 8 * * 1 /path/to/weekly/program_name last:15 8 1 * * /path/to/monthly/program_name
In each case, the daily program is run at 8:15 a.m. (local time). The weekly program is run only on Monday; the monthly program is run on the first of the month. Note that, if the program produces output on STDOUT or STDERR, the output will be e-mailed to the local user that owns the crontab entry (www-data in this case). This is rarely useful. Try to ensure that programs running under cron in this way do not produce such output. Under Windows, the Task Scheduler can be used to similar ends.