纯文本:
#!/usr/bin/env python3 #coding: utf-8 import smtplib from email.mime.text import MIMEText from email.header import Header sender = '***' receiver = '***' subject = 'python email test' smtpserver = 'smtp.163.com' username = '***' password = '***' msg=MIMEText(_text="你好",_charset='utf-8')#中文需参数‘utf-8’,单字节字符不需要 msg['Subject'] = Header(subject, 'utf-8') msg['From']=sender msg["To"]=receiver smtp = smtplib.SMTP() smtp.connect('smtp.exmail.qq.com') smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit()
HTML格式:
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() msgRoot['Subject'] = 'test message' msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>good!','html','utf-8') msgRoot.attach(msgText) fp = open('e:\1.jpg', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) smtp = smtplib.SMTP() smtp.connect('smtp.exmail.qq.com') smtp.login(username, password) smtp.sendmail(sender, receiver, msgRoot.as_string()) smtp.quit()
附件邮件:
#coding: utf-8 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' #构造附件 att = MIMEText(open('h:\python\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('smtp.163.com') smtp.login(username, password) smtp.sendmail(sender, receiver, msgRoot.as_string()) smtp.quit()