python發送郵件和附件
阿新 • • 發佈:2019-03-09
tex -s blog 登錄 51cto port nag 使用 utf8 發送郵件的時候,需要發送人,收件人,和一臺郵件服務器,這裏使用python發送一個郵件,主要需要引入smtplib和email庫。
下面是源碼,粘貼即可用:
下面是源碼,粘貼即可用:
#!/usr/bin/env python3 # coding: utf-8 import smtplib import time import sys from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart # 發送郵件 def SendMail(mail_list, subject, content): from_mail = ‘這裏填入發件人郵箱‘ temp_msg = ‘武松申請了車費報銷‘ msg = MIMEText(‘</pre><p>‘ + temp_msg + ‘</p><a href="/agree">同意</a>,<a href="/disagree">不同意</a><pre>‘, ‘html‘,‘utf-8‘) msg[‘Subject‘] = subject msg[‘From‘] = from_mail msg[‘To‘] = mail_list msg[‘date‘] = time.strftime(‘%a, %d %b %Y %H:%M:%S %z‘) smtp_server = ‘這裏填入郵件服務器的地址‘ s = smtplib.SMTP(smtp_server) s.login("填入登錄郵件服務器的郵箱", "填入郵箱密碼") s.sendmail(from_mail, mail_list.split(","), msg.as_string()) s.quit() # 發送郵件帶附件 def SendMailWithAttachment(mail_list, subject, content, attachment): from_mail = ‘這裏填入發件人郵箱‘ msg = MIMEMultipart() msg[‘Subject‘] = subject msg[‘From‘] = from_mail msg[‘To‘] = mail_list msg[‘date‘] = time.strftime(‘%a, %d %b %Y %H:%M:%S %z‘) msg.attach(MIMEText(content, ‘html‘, ‘utf-8‘)) att = MIMEText(open(attachment, ‘rb‘).read(), ‘base64‘, ‘utf8‘) att["Content-Type"] = ‘application/octet-stream‘ att["Content-Disposition"] = ‘attachment; filename="%s"‘ % attachment msg.attach(att) smtp_server = ‘這裏填入郵件服務器的地址‘ s = smtplib.SMTP(smtp_server) s.login("填入登錄郵件服務器的郵箱", "填入郵箱密碼") s.sendmail(from_mail, mail_list.split(","), msg.as_string()) s.quit() if __name__ == ‘__main__‘: if len(sys.argv) < 4: print(‘Usage:‘, sys.argv[0], ‘ mail_list subject content [attachment]‘) sys.exit(1) content = "" if len(sys.argv) == 4: SendMail(sys.argv[1], sys.argv[2], content) else: SendMailWithAttachment(sys.argv[1], sys.argv[2], content, sys.argv[4])
你需要修改的地方是:
from_mail:發件人信息
temp_msg:發送的內容
smtp_server:郵件服務器地址
s.login:郵件服務器登錄名和密碼
命令行發送:
python3 sendmail.py ‘[email protected]‘ ‘python send mail‘ ‘leran is fun‘
顯示效果:
python發送郵件和附件