Last active
September 28, 2019 09:36
-
-
Save ws2356/66fbc76ed42b629a163dce8658f1fb00 to your computer and use it in GitHub Desktop.
send email using python3 smtplib
This file contains hidden or 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 python3 | |
import os | |
import sys | |
import smtplib | |
from email.mime.application import MIMEApplication | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
from email.utils import COMMASPACE | |
SMTP_ADDR = 'smtp.office365.com' | |
SMTP_PORT = 587 | |
SMTP_ENC = 'STARTTLS' | |
SMTP_USER = '[email protected]' | |
SMTP_PASSWORD = os.environ.get('SMTP_PASSWORD', None) | |
if SMTP_PASSWORD is None: | |
print('没有发件服务器密码,无法自动发布') | |
sys.exit(1) | |
MAIL_CONTENT = '查看附件。' | |
MAIL_CONTENT_HTML_FILE = 'backend/resume.html' | |
MAIL_SUBJECT = '简历更新' | |
MAIL_SENDER = '[email protected]' | |
MAIL_RECEIVERS = ['[email protected]'] | |
MAIL_ATTACHMENTS = [ | |
'backend/resume.pdf', | |
'backend/resume.en.pdf', | |
'backend/resume.md', | |
'backend/resume.en.md'] | |
def main(): | |
try: | |
s = smtplib.SMTP(host=SMTP_ADDR, port=SMTP_PORT) | |
s.starttls() | |
except Exception as e: | |
print('failed to connect to smtp host: %s, port: %d, error: %s' % (SMTP_ADDR, SMTP_PORT, e)) | |
return | |
try: | |
s.login(SMTP_USER, SMTP_PASSWORD) | |
except Exception as e: | |
print( | |
'failed to login to smtp host: %s, port: %d, user: %s, password: %s, error: %s' % | |
(SMTP_ADDR, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, e)) | |
return | |
try: | |
msg = MIMEMultipart() | |
msg['Subject'] = MAIL_SUBJECT | |
msg['From'] = MAIL_SENDER | |
msg['To'] = COMMASPACE.join(MAIL_RECEIVERS) | |
with open(MAIL_CONTENT_HTML_FILE, "r") as pfile: | |
txt = MIMEText(pfile.read(), 'html') | |
msg.attach(txt) | |
for f in MAIL_ATTACHMENTS: | |
with open(f, "rb") as pfile: | |
part = MIMEApplication( | |
pfile.read(), | |
Name=os.path.basename(f) | |
) | |
part['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(f) | |
msg.attach(part) | |
s.sendmail(MAIL_SENDER, MAIL_RECEIVERS, msg.as_string()) | |
except Exception as e: | |
print('failed to send to smtp host: %s, port: %d, user: %s, password: %s, msg: %s, error: %s' % | |
(SMTP_ADDR, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, msg.as_string(), e)) | |
try: | |
s.quit() | |
except Exception as e: | |
print('did send to smtp host: %s, port: %d, user: %s, password: %s, msg: %s, but failed to quit, error: %s' % | |
(SMTP_ADDR, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, msg.as_string(), e)) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment