1、发送 html 文本内容的邮件
# smtplib 负责发送邮件 import smtplib # MIMEText 负责构造邮件内容 from email.mime.text import MIMEText # Header 是用来构建邮件头的 from email.header import Header smtpServer= "smtp.163.com" sender = "zhengying0813@163.com" passWord = "MDZWNINBZEDKXXX" receiver = "zhengying0813@163.com" subject = "Python email test" # 三个参数:第一个为文本内容,第二个 html 设置文本格式,第三个 utf-8 设置编码 msg = MIMEText("<html><h1>你好!</h1></html>","html","utf-8") # 定义邮件主题 msg["Subject"] = Header(subject,"utf-8") msg["From"] = Header(sender,"utf-8") msg["To"] = Header(receiver) smtp = smtplib.SMTP() smtp.connect(smtpServer) # 登录 SMTP 服务器 smtp.login(sender,passWord) # msg.as_string() 把 MIMEText 变成 str 对象 smtp.sendmail(sender,receiver,msg.as_string()) smtp.quit()
2、发送带附件的邮件
import smtplib from email.mime.text import MIMEText from email.header import Header from email.mime.multipart import MIMEMultipart smtpServer= "smtp.163.com" sender = "zhengying0813@163.com" passWord = "MDZWNINBZEDKCXXX" receiver = "zhengying0813@163.com" subject = "Python email test" # 创建一个带附件的实例 msg = MIMEMultipart() msg["Subject"] = Header(subject,"utf-8") msg["From"] = Header(sender,"utf-8") msg["To"] = Header(receiver) # log.txt 为报告文件 file = open("log.txt","rb").read() att = MIMEText(file,"base64","utf-8") # 这里的 filename 定义邮件中显示什么名字 att["Content-Disposition"] = 'attachment; filename="log.txt"' # 添加文件到邮件附件中去 msg.attach(att) smtp = smtplib.SMTP() smtp.connect(smtpServer) smtp.login(sender,passWord) smtp.sendmail(sender,receiver,msg.as_string()) smtp.quit()