Skip to content

Instantly share code, notes, and snippets.

@evan-burke
Last active February 4, 2022 01:14
Show Gist options
  • Save evan-burke/0d8252007f928a6ec69cc137352ca05e to your computer and use it in GitHub Desktop.
Save evan-burke/0d8252007f928a6ec69cc137352ca05e to your computer and use it in GitHub Desktop.
python smtp quick reference
# work in progress. I'm not 100% sure on distinction between legacy compat32 api and new API yet, so grain of salt and all.
import email
# __init__ is empty in email.mime so you need to import specific files/modules.
import email.mime.multipart
# use this for creating a message from scratch. You'll need to add all headers and parts etc.
# appears to be an email.message.Message, as it has all of those functions, though type is email.mime.multipart.MIMEMultipart
msg = email.mime.multipart.MIMEMultipart()
# email.message.Message:
# https://docs.python.org/3/library/email.compat32-message.html#compat32-message
# email.message.EmailMessage:
# https://docs.python.org/3/library/email.message.html#email.message.EmailMessage
# to read from a file:
p = email.parser.Parser()
with open(email_file, 'r') as f:
# this is also an email.message.Message
m = p.parse(f)
# sending:
import smtplib
# just try connecting, should show 250 ok
with smtplib.SMTP("pfx.delivio.us") as smtp:
print(smtp.noop())
# ref: http://pymotw.com/2/smtplib/
# smtp.sendmail(...) msg is an ascii string, or a byte string
# smtp.send_message(...) similar, but msg is an email.message.Message
# https://docs.python.org/3/library/smtplib.html#smtplib.SMTP.sendmail
# https://docs.python.org/3/library/smtplib.html#smtplib.SMTP.send_message
# note you'll need to do your own mx lookup
with smtplib.SMTP(mx) as smtp:
r = smtp.send_message(msg=m)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment