Created
October 22, 2014 12:21
-
-
Save harrifeng/1635c75c9b082ad170dd to your computer and use it in GitHub Desktop.
Send email through a smtp server (can be local mailcatcher)
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
# 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