欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python发送邮件,带附件

程序员文章站 2024-03-23 17:29:40
...
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

#  ../img.zip 发送的是上级目录下的img.zip文件
def send_mail(user, pwd, to):
    msg = MIMEMultipart()
    body = MIMEText("这里你可以写点HTML的内容,邮件可以回显", 'HTML', 'utf-8')  # 邮件内容
    msg['Subject'] = Header("发送邮件", 'utf-8')  # 邮件的标题
    msg['From'] = user
    msg['To'] = to
    msg.attach(body)
    #
    # 添加附件
    att = MIMEText(open("../img.zip", "rb").read(), "base64", "utf-8")  # 打开附件地址
    att["Content-Type"] = "application/octet-stream"
    att["Content-Disposition"] = 'attachment; filename="image.zip"'
    msg.attach(att)

    # 发送邮件
    s = smtplib.SMTP_SSL("smtp.exmail.qq.com")
    s.login(user, pwd)  # 登录邮箱的账户和密码
    s.sendmail(user, to, msg.as_string())  # 发送邮件
    s.quit()
    print("邮件发送成功")