Sending mail from a Bash shell script Sending mail from a Bash shell script shell shell

Sending mail from a Bash shell script


Since Mac OS X includes Python, consider using a Python script instead of a Bash script. I haven't tested the sending portion, but it follows the standard example.

Python script

# SettingsSMTP_SERVER = 'mail.myisp.com'SMTP_PORT = 25SMTP_USERNAME = 'myusername'SMTP_PASSWORD = '$uper$ecret'SMTP_FROM = 'sender@example.com'SMTP_TO = 'recipient@example.com'TEXT_FILENAME = '/script/output/my_attachment.txt'MESSAGE = """This is the messageto be sent to the client."""# Now construct the messageimport smtplib, emailfrom email import encodersimport osmsg = email.MIMEMultipart.MIMEMultipart()body = email.MIMEText.MIMEText(MESSAGE)attachment = email.MIMEBase.MIMEBase('text', 'plain')attachment.set_payload(open(TEXT_FILENAME).read())attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(TEXT_FILENAME))encoders.encode_base64(attachment)msg.attach(body)msg.attach(attachment)msg.add_header('From', SMTP_FROM)msg.add_header('To', SMTP_TO)# Now send the messagemailer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)# EDIT: mailer is already connected# mailer.connect()mailer.login(SMTP_USERNAME, SMTP_PASSWORD)mailer.sendmail(SMTP_FROM, [SMTP_TO], msg.as_string())mailer.close()

I hope this helps.


Actually, "mail" works just as well.

mail -s "subject line" name@address.ext < filename

works perfectly fine, as long as you have SMTP set up on your machine. I think that most Macs do, by default.

If you don't have SMTP, then the only thing you're going to be able to do is go through Mail.app. An ALTERNATIVE way to go through mail.app is via AppleScript. When you tell Mail.app to send mail via AppleScript you can tell it to not pop up any windows... (this does still require Mail.app to be configured).

Introduction to Scripting Mail has a good description of how to work with mail in AppleScript.


There is a program called Sendmail.

You probably don't want to use the -bs command unless you are sending it as raw SMTP like Martin's example. -bs is for running an SMTP server as a deamon. Sendmail will send directly to the receiving mail server (on port 25) unless you override it in the configuration file. You can specify the configuration file by the -C paramter.

In the configuration, you can specify a relay server (any mail server or sendmail running -bs on another machine)

Using a properly configured relay server is good idea because when IT manages mail servers they implement SPF and domain keys. That keeps your mail out of the junk bin.

If port 25 is blocked you are left with two options.

  1. Use the corporate SMTP server.
  2. Run sendmail -bd on a machine outside ofthe corporate firewall that listenson a port other than 25.

I believe you can add configuration parameters on the command line. What you want is the SMART_HOST option. So call Sendmail like sendmail -OSMART_HOST=nameofhost.com.