通过服务器发送 Foxmail 邮件(添加附件)


import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
import os

sender = 'tonn.he@foxmail.com'  #发送人邮件
# receivers = ['test@163.com','test@vip.qq.com']  # 接收多个邮件,可设置为你的QQ邮箱或者其他邮箱
receivers = ['tonn.he@foxmail.com']  # 接收邮件
mail_host="smtp.qq.com"  #设置服务器
mail_port=465 #设置服务器
mail_user="tonn.he@foxmail.com"    #邮件登陆名称
mail_pass="************"    #密码为生成的授权码


# 封装一个方法直接传入邮件标题和内容
def post_email(title, context,files=[]):
    message=MIMEMultipart()
    message['From'] = Header(sender)  # 发送者
    message['To'] = Header(str(";".join(receivers)))  # 接收者
    message['Subject'] = Header(title)#邮件主旨
    #邮件内容
    cont=MIMEText(context, 'plain', 'utf-8')
    message.attach(cont)
    #添加附件
    if len(files)>0:
        for path in files:
            if os.path.exists(path):#路径存在则添加
                file_name=path.split('\\')[-1]
                print(file_name)
                #添加附件
                part = MIMEApplication(open(path, 'rb').read(), _subtype="base64", _charset="utf-8")
                part.add_header('content-disposition', 'attachment', filename=file_name)
                message.attach(part)

    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, mail_port)#连接服务器
        smtpObj.login(mail_user, mail_pass)#登录
        smtpObj.sendmail(sender, receivers, message.as_string())#发送邮件
        smtpObj.quit()#退出
        return "发送成功"
    except smtplib.SMTPException:
        return smtplib.SMTPException

if __name__ == '__main__':
    files=[r"C:\Users\Administrator\Desktop\test\Test.xlsx",
           r"C:\Users\Administrator\Desktop\test\微信截图_20190815152527.png",r"C:\Users\Administrator\Desktop\test\新建文本文档.txt"]
    result = post_email("来自于测试数据", "今天测试一下python是否可以发送邮件成功。",files)
    print(result)