Last active
December 6, 2018 21:24
-
-
Save guoqiao/d42f626c76bc1f9fff3d11ca00acda15 to your computer and use it in GitHub Desktop.
Send email with SMTP over STARTTLS in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding=utf8 | |
""" | |
Send email with SMTP | |
Add env vars in your ~/.bashrc and source it: | |
export EMAIL_HOST=smtp.example.com | |
export EMAIL_PORT=587 | |
export EMAIL_USERNAME=sender@example.com | |
export EMAIL_PASSWORD=PASSWORD | |
export EMAIL_TO_LIST=foo@gmail.com,bar@example.com | |
""" | |
import os | |
import smtplib | |
EMAIL_HOST = os.environ['EMAIL_HOST'] | |
EMAIL_PORT = int(os.environ['EMAIL_PORT']) | |
EMAIL_USERNAME = os.environ['EMAIL_USERNAME'] | |
EMAIL_PASSWORD = os.environ['EMAIL_PASSWORD'] | |
# comma separated email list | |
EMAIL_TO_LIST = os.environ['EMAIL_TO_LIST'].split(',') | |
EMAIL_MESSAGE = "From: {}\r\nTo: {}\r\nSubject:{}\r\n\r\n{}".format( | |
EMAIL_USERNAME, | |
','.join(EMAIL_TO_LIST), | |
'this is email subject', | |
'this is email body') | |
if EMAIL_PORT == 25: | |
# smtp default, may be deprecated | |
server = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) | |
elif EMAIL_PORT == 587: | |
# smtp over starttls, a improved solution | |
server = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) | |
server.starttls() | |
elif EMAIL_PORT == 465: | |
# smtp over ssl, a final solution | |
server = smtplib.SMTP_SSL(EMAIL_HOST, EMAIL_PORT) | |
server.set_debuglevel(1) | |
server.login(EMAIL_USERNAME, EMAIL_PASSWORD) | |
server.sendmail(EMAIL_USERNAME, EMAIL_TO_LIST, EMAIL_MESSAGE) | |
server.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment