时间:2021-07-01 10:21:17 帮助过:32人阅读
发送 HTML 形式的邮件
发送 HTML 形式的邮件,需要 email.mime.text 中的 MIMEText 的 _subtype 设置为 html,并且 _text 的内容应该为 HTML 形式。
import smtplib from email.mime.text import MIMEText sender = '***' receiver = '***' subject = 'python email test' smtpserver = 'smtp.163.com' username = '***' password = '***' msg = MIMEText(u'''''','html','utf-8') msg['Subject'] = subject smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit()你好
注意:这里的代码并没有把异常处理加入,需要读者自己处理异常。
发送带图片的邮件
发送带图片的邮件是利用 email.mime.multipart 的 MIMEMultipart 以及 email.mime.image 的 MIMEImage:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage sender = '***' receiver = '***' subject = 'python email test' smtpserver = 'smtp.163.com' username = '***' password = '***' msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'test message' msgText = MIMEText( ''' Some HTML text and an image.good!''', 'html', 'utf-8') msgRoot.attach(msgText) fp = open('/Users/1.jpg', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '') msgRoot.attach(msgImage) smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(username, password) smtp.sendmail(sender, receiver, msgRoot.as_string()) smtp.quit()
发送带附件的邮件
发送带附件的邮件是利用 email.mime.multipart 的 MIMEMultipart 以及 email.mime.image 的 MIMEImage,重点是构造邮件头信息:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText sender = '***' receiver = '***' subject = 'python email test' smtpserver = 'smtp.163.com' username = '***' password = '***' msgRoot = MIMEMultipart('mixed') msgRoot['Subject'] = 'test message' # 构造附件 att = MIMEText(open('/Users/1.jpg', 'rb').read(), 'base64', 'utf-8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="1.jpg"' msgRoot.attach(att) smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(username, password) smtp.sendmail(sender, receiver, msgRoot.as_string()) smtp.quit()