email from the shell

Previously I showed a php script to send email. You can use php as a shell language as well as a web development language. PHP has ready made functions for this, so it is kind of an easy thing to do. Here is an example of a straight email shell script using bash.

#!/bin/bash

sendmail=”/usr/sbin/postfix”

recipient=”user@domain.com, user2@domain2.com”

( cat < < EOF
From: user@domain.com
To: $recipient
Subject: Test emai from bash

This is a test email generated from a shell script.

EOF

echo ""; echo ""
echo "Submitted on $(date)"
) | sendmail -t

exit 0

You have to have either sendmail or postfix running and set up on your mac. OS X is now shipping with Postfix.

3 Responses to “email from the shell”

  1. Shawn Holwegner Says:

    A more apropos solution is to use the ‘mail’ command; sendmail -t is much like crafting your own tools when any standard screwdriver will do.

    A comparable syntax to your note above is: echo stuff | mail -s ’subject here’ user@domain.biz.

    As with your prior article, handling mail can become amazingly complex and archaic at times. For PHP, I’d strongly sugggest a prerolled solution such as PHPMailer - so you don’t have to contend wuith the multitude of problems which come with multipart, mime, attachments, et al.

    A quick little hack that I used years ago to automatically send attachments from the command line (via crontab) was to install the mailer ‘mutt’ on the system, then ‘mutt user@where.org -s ‘Attachment for $DATE’ -a attachfile

  2. Miles Says:

    I see that the special characters and subsequent text were stripped from my post. I’ll try again:

    ( cat < < EOF
    should be:
    ( cat << EOF
    That is, there should be no space between the < symbols.

    Also, the curly quotes on the sendmail and recipient lines should be changed to straight quotes.

  3. bradrice Says:

    Correct. Thanks for point this out. My blog converts straight to curly quotes. Sorry about any inconvenience. I’ll see if I can fix that for future posts. Thanks for pointing out the error in the less than symbols not being together.

    -Brad