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...
MAILGUN_SMTP_LOGIN: postmaster@sandbox123...123.mailgun.org
MAILGUN_SMTP_PASSWORD: abcd123
MAILGUN_SMTP_PORT: 587
MAILGUN_SMTP_SERVER: smtp.mailgun.org
Copy and paste this into a file with the name mailgun.py
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())
s.quit()
In your main.py 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
text = "your message"
subject = "subject of message"
recipient = "myself@email.com"
sender = "foo@" + str(os.environ["MAILGUN_DOMAIN"])
smtp_login = str(os.environ["MAILGUN_SMTP_LOGIN"])
smtp_server = os.environ["MAILGUN_SMTP_SERVER"]
password = os.environ["MAILGUN_SMTP_PASSWORD"]
port = int(os.environ["MAILGUN_SMTP_PORT"])send_message_mailgun(text, subject, recipient, sender, smtp_login, password, smtp_server, port)
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.