验证中...
片段 1 片段 2
读取html格式的测试报告,用163邮箱发送
原始数据 复制代码
import smtplib
from email.mime.text import MIMEText
from email.header import Header
with open("C:\\Users\\Administrator\\Desktop\\report.html","rb")as report:
mail_body=report.read()
smtpserver="smtp.163.com"
port="25"
user="user@163.com"
password="password" #密码为邮箱客户端的授权码
receiver="user@game2palm.com"
sender="user@163.com"
subject="python test mail"
msg=MIMEText(mail_body,'html','utf-8')
#"subject,From,To"3个参数一定要注意,稍有差错就会被163邮箱认定为垃圾邮件而拒绝
msg['subject']=Header(subject,'utf-8')
msg['From']= sender
msg['To']=receiver
try:
smtp=smtplib.SMTP()
smtp.connect(smtpserver,port)
smtp.login(user,password)
smtp.sendmail(sender,receiver,msg.as_string())
print("邮件已发送")
except smtplib.SMTPException as e:
print(e,"邮件发送失败")
finally:
smtp.quit()
增加发送附件功能
原始数据 复制代码
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
with open("C:\\Users\\Administrator\\Desktop\\report.html","rb")as report:
mail_body=report.read()
smtpserver="smtp.163.com"
port="25"
user="user@163.com"
password="password" #密码为邮箱客户端的授权码
receiver="user@game2palm.com"
sender="user@163.com"
subject="python test mail"
html=MIMEText(mail_body,'html','utf-8')
msg=MIMEMultipart() #单一种内容的时候可以用MIMEText(),但是多种内容的邮件就必须使用MIMEMultipart()方法将正文内容分段
msg['subject']=Header(subject,'utf-8')
msg['From']= sender
msg['To']=receiver
msg.attach(html) #将html分段内容添加进邮件内容
#下面三行是添加附件代码
att=MIMEApplication(mail_body)
att.add_header('Content-Disposition', 'attachment', filename="report.html")
msg.attach(att)
try:
smtp=smtplib.SMTP()
smtp.connect(smtpserver,port)
smtp.login(user,password)
smtp.sendmail(sender,receiver,msg.as_string())
print("邮件已发送")
except smtplib.SMTPException as e:
print(e,"邮件发送失败")
finally:
smtp.quit()

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助