Automate e-mail sending from Heroku with Python

Add Mailgun to the add-ons (there are other options, but this one was for me the easiest to configure). You can do it via the CLI with:

heroku addons:create mailgun:Starter 

Or you can do it via the user-interface via resources and in the add-ons input typing Mailgun:

See your heroku mailgun variables in the CLI with:

heroku config

You will see something like this:

MAILGUN_API_KEY:         123..
MAILGUN_DOMAIN: sandbox123...
MAILGUN_PUBLIC_KEY: pubkey-123...

Copy and paste this into a file with the name

import smtplib
from email.mime.text import MIMEText

def send_message_mailgun(text, subject, recipient, sender, smtp_login, password, smtp_server, port):
msg = MIMEText(text)
msg['Subject'] = subject
msg['To'] = recipient
msg['From'] = sender
s = smtplib.SMTP(smtp_server, port)
s.login(smtp_login, password)
s.sendmail(msg['From'], msg['To'], msg.as_string())

In your or another python script from which you want to send the mail, add your e-mail recipient, text and subject and add references to Mailgun variables:

from mailgun import send_message_mailgun

The mail will most likely end up in the spam box of the recipient so the sender address needs to be unspammed in the email account of the recipient.



MD, PhD with a heart for software development,

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store