Skip to content

Instantly share code, notes, and snippets.

@harrifeng
Created October 22, 2014 12:21
Show Gist options
  • Save harrifeng/1635c75c9b082ad170dd to your computer and use it in GitHub Desktop.
Save harrifeng/1635c75c9b082ad170dd to your computer and use it in GitHub Desktop.
Send email through a smtp server (can be local mailcatcher)
# http://mailcatcher.me/
SMTP_SERVER = 'localhost'
SMTP_PORT = 1025
SMTP_USERNAME = 'myusername'
SMTP_PASSWORD = '$uper$ecret'
SMTP_FROM = '[email protected]'
SMTP_TO = '[email protected]'
TEXT_FILENAME = '/Users/i309511/tmp/hello.py'
MESSAGE = """This is the message
to be sent to the client.
"""
# Now construct the message
import smtplib, email
from email import encoders
import os
msg = email.MIMEMultipart.MIMEMultipart()
body = email.MIMEText.MIMEText(MESSAGE)
attachment = email.MIMEBase.MIMEBase('text', 'plain')
attachment.set_payload(open(TEXT_FILENAME).read())
attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(TEXT_FILENAME))
encoders.encode_base64(attachment)
msg.attach(body)
msg.attach(attachment)
msg.add_header('From', SMTP_FROM)
msg.add_header('To', SMTP_TO)
# Now send the message
mailer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
# EDIT: mailer is already connected
# mailer.connect()
# If you need auth, please uncomment following line
# mailer.login(SMTP_USERNAME, SMTP_PASSWORD)
mailer.sendmail(SMTP_FROM, [SMTP_TO], msg.as_string())
mailer.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment