Mailing From Expect
In the previous section, I suggested using mail as a last ditch attempt to contact the user or perhaps just a way of letting someone know what happened. Most versions of cron automatically mail logs back to users by default, so it seems appropriate to cover mail here. Sending mail from a background process is not the most flexible way of communicating with a user, but it is clean, easy, and convenient.
People usually send mail interactively, but most mail programs do not need to be run with spawn. For example, /bin/mail can be run using exec with a string containing the message.
The lines of the message should be separated by newlines. The variable to names the recipient in this example:
exec /bin/mail $to << "this is a message\nof two lines\n"
There are no mandatory headers, but a few basic ones are customary. Using variables and physical newlines makes the next example easier to read:
exec /bin/mail $to << "From: $from To: $to From: $from Subject: $subject $body"
To send a file instead of a string, use the < redirection.
You can also create a mail process and write to it:
set mailfile [open "|/bin/mail $to" w] puts $mailfile "To: $to" puts $mailfile "From: $from" puts $mailfile "Subject: $subject"
This approach is useful when you are generating lines one at a time, such as in a loop:
while {....} {
... ;# compute line
puts $mailfile "computed another line: $line"
}
To send the message, just close the file.
close $mailfile
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access