zl程序教程

您现在的位置是:首页 >  工具

当前栏目

发邮件 文字+ 附件的方法(QQ or 网易 邮箱)

QQ方法 or 文字 邮箱 网易 附件 发邮件
2023-09-27 14:25:20 时间

#coding:utf-8
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# ---------- ---------- 1. 跟发件相关的参数 ------
# 发邮件相关的参数
# 网易邮箱用这个
# smtpserver="smtp.163.com" #发件服务器
# port=0 #端口
# sender="#####@163.com"#发件的邮箱
# psw="#####"#授权码
# receiver=["######@qq.com"]#收件的邮箱

# QQ邮箱用这个
smtpserver="smtp.qq.com"#发件服务器
port=465#端口
sender="#####@qq.com"#发件的邮箱
psw="######"#授权码
receiver=["######@163.com"]#收件的邮箱

# ---------- ---------- 2. 编辑邮 件的内容 ------------

# 读取附件文件
file_path = "D:/report.html" #附件地址
with open(file_path, "rb") as fp:
  mail_body = fp.read()

# 装载信息和内容
msg = MIMEMultipart()
msg["from"] = sender
msg["to"]=";".join(receiver)

msg["subject"] = "这个我的主题 "
body="<p>这个是发送的163邮件</p>"

# 指定展示正文内容,body改为mail_body即展示附件内容
body = MIMEText(body, "html","utf-8")
msg.attach(body)

# 附件参数
att = MIMEText(mail_body, "base64", "utf-8")
att["Content-Type"] = "application/octet-stream"
att["Content-Disposition"] = 'attachment; filename="test_report.htm"'
msg.attach(att)


# ---------- ---------- 3. 发送邮件------
try:
  # 网易邮箱登录
  smtp = smtplib.SMTP()
  smtp.connect(smtpserver)
  smtp.login(sender, psw)
except:
  # QQ邮箱登录
  smtp = smtplib.SMTP_SSL(smtpserver, port)
  smtp.login(sender, psw)
smtp.sendmail(sender,receiver,msg.as_string())#发送
smtp.quit()#关闭