Sending mail from a Bash shell script

Previously, this answer was based on the default inclusion of a recent Python on Mac OS X. Since then, the Python ecosystem has evolved and Python is not available on a clean install. This answer has been updated for modern systems, but is much more involved and exceeds the scope of the original poster’s request.

Python and it’s built-in standard library provides some nice facilities for sending email if you’re willing to install it. Consider using the stock installer or installing homebrew followed by brew install python.

From there, customize the following script based on stock examples to suit your needs.

# Settings

SMTP_SERVER = 'mail.myisp.com'
SMTP_PORT = 25
SMTP_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 message
to be sent to the client.
"""

# Now construct the message
import pathlib
import smtplib
import email.message

msg = email.message.EmailMessage()
msg.set_content(MESSAGE)
text_path = pathlib.Path(TEXT_FILENAME)
msg.add_attachment(
    text_path.read_text(),
    maintype="text",
    subtype="plain",
    filename=text_path.name,
)
msg['From'] = SMTP_FROM
msg['To'] = SMTP_TO
# msg['Subject'] = SMTP_SUBJECT

# Now send the message
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as mailer:
    mailer.login(SMTP_USERNAME, SMTP_PASSWORD)
    mailer.send_message(msg)

I hope this helps.

Leave a Comment