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

python基础之发送带附件邮件

程序员文章站 2022-03-16 08:54:13
...
import os,time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


password = ""		# 授权码,非邮箱密码,在邮箱设置授权项操作
email_host = "smtp.qq.com"
send_user = "[email protected]"
send_to = "[email protected]"
email_port = '465'	# 带附件,故取465

def senEmail(file_new):
    # 读取最新的报告文件
    msg = MIMEMultipart()
    with open(file_new, 'rb')as filename:
        mail_body = filename.read()
    print('正文:',mail_body)

    # 定义文件正文
    msg.attach(MIMEText(mail_body, _subtype='html', _charset='utf-8'))
    # 定义标题
    msg['Subject'] = u'xxx测试报告'
    str_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    msg['date'] = str_time
    # 添加附件
    att1 = MIMEText(open(file_new, 'rb').read(), 'base64', 'utf-8')
    att1['Conntent-Type'] = 'application/octet-stream'
    filename = file_new.split('/')
    att1["Content-Disposition"] = 'attachment; filename = ' + filename[-1] + ' ' #字符串内应用变量两种写法,或者'{}'.format(xx)
    # att1["Content-Disposition"] = 'attachment; filename = %s '%(filename[-1])
    msg.attach(att1)
    smtp = smtplib.SMTP_SSL(email_host,email_port)  # py3.7以上版本写法smtplib.SMTP_SSL(mail_host, 465),其他的smtplib.SMTP_SSL(),否则报错
    smtp.set_debuglevel(1)
    smtp.login(send_user, password)
    try:
        smtp.sendmail(send_user,send_to, msg.as_string())   # 加as_string(),不然报closed错
        print('邮箱发送成功!')
    except:
        print('发送不成功')
    smtp.quit()


"""获取最后一份报告文件并发送邮件"""


def sendReport():
    """获取最新的文件"""
    result_dir = './report/'
    lists = os.listdir(result_dir)
    lists.sort(key=lambda fn: os.path.getmtime(result_dir + fn) if not os.path.isdir(result_dir + fn) else 0)
    print(u'最新生成的报告' + lists[-1])
    # 找到最新生成的文件
    file_new = os.path.join(result_dir, lists[-1])
    senEmail(file_new)


if __name__ == '__main__':
    sendReport()

注:此文参考了其他博客