Sending mail from a Bash shell script


I am writing a Bash shell script for Mac that sends an email notification by opening an automator application that sends email out with the default mail account in The automator application also attaches a text file that the script has written to. The problems with this solution are

  1. It is visible in the GUI when sending
  2. It steals focus if Mail is not the current application
  3. It is dependent on's account setup being valid in the future

I figure to get around those shortcomings I should send the mail directly from the script by entering SMTP settings, address to send to, etc. directly in the script. The catch is I would like to deploy this script on multiple computers (10.5 and 10.6) without enabling Postfix on the computer. Is it possible to do this in the script so it will run on a base Mac OS X install of 10.5. and 10.6?

Update: I've found the -bs option for Sendmail which seems to be what I need, but I'm at a loss of how to specify settings.

Also, to clarify, the reason I'd like to specify SMTP settings is that mails from localhost on port 25 sent out via Postfix would be blocked by most corporate firewalls, but if I specify the server and an alternate port I won't run into that problem.

10/5/2013 9:23:14 PM

Accepted Answer

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

# Settings

SMTP_USERNAME = 'myusername'
SMTP_PASSWORD = '$uper$ecret'
SMTP_TO = ''

TEXT_FILENAME = '/script/output/my_attachment.txt'
MESSAGE = """This is the message
to be sent to the client.

# Now construct the message
import smtplib, email
from email import encoders
import os

msg = email.MIMEMultipart.MIMEMultipart()
body = email.MIMEText.MIMEText(MESSAGE)
attachment = email.MIMEBase.MIMEBase('text', 'plain')
attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(TEXT_FILENAME))
msg.add_header('From', SMTP_FROM)
msg.add_header('To', SMTP_TO)

# Now send the message
mailer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
# EDIT: mailer is already connected
# mailer.connect()
mailer.sendmail(SMTP_FROM, [SMTP_TO], msg.as_string())

I hope this helps.

10/5/2013 9:18:42 PM

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 An ALTERNATIVE way to go through is via AppleScript. When you tell to send mail via AppleScript you can tell it to not pop up any windows... (this does still require to be configured).

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow