• 如何用Python发送电子邮件(含附件)


    电子邮件自诞生到现在,依旧是重要的通讯工具.在日常工作大量的告警,自动化报表依旧是通过邮件来完成.以前一直是只发送html正文,前两天遇到了发附件的情况,顺道解决了邮件名乱码的问题,记录一下

    正常发送邮件

    电子邮件到今天这个时间点,处理垃圾邮件的管控,很多云服务商和电子邮件服务商已经不再支持smtp通过25端口来发送,而要使用ssl加密的465端口

    本文演示基本腾讯企业邮箱,估计QQ个人邮箱也一样.

    Python:3.8.2

    #!/usr/local/bin/python3.8.2
    # -*- coding: utf-8 -*-
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    
    mail_host = 'smtp.exmail.qq.com'
    mail_user = 'xxx@xxx.xx'
    mail_pass = 'xxxxxx'
    mail_from = 'rainbird'
    mail_to   = 'xxx@xxx.xx'
    mail_title= "rainbird's mac book"
    me = mail_from +"<"+mail_user+">"
    
    mail_body = '/result_report.html'
    msg = MIMEText(mail_body,_subtype='html',_charset='utf8')
    msg['Subject']  = mail_title
    msg['From']     = me
    msg['To']       = mail_to
    try:
        s = smtplib.SMTP_SSL(host=mail_host)
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(me, mail_to, msg.as_string())
        s.close()
        print('send mail success!')
    except Exception as e:
        print(e)

    发送附件

    这部分比较困难的部分就是邮件名乱码.经过尝试指定邮件名UTF8编码,就可以了.

    #!/usr/local/bin/python3.8.2
    # -*- coding: utf-8 -*-
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    
    mail_host = 'smtp.exmail.qq.com'
    mail_user = 'xxx@xxx.xx'
    mail_pass = 'xxxxxx'
    mail_from = 'rainbird'
    mail_to   = 'xxx@xxx.xx'
    mail_title= "rainbird's mac book"
    me = mail_from +"<"+mail_user+">"
    
    def file_get_content(file_name):
        with open (file_name,'r') as f:
            return f.read()
    
    mail_body = '/result_report.html'
    mail_att  = '/result.html'
    msg = MIMEMultipart()
    msg['Subject']  = mail_title
    msg['From']     = me
    msg['To']       = mail_to
    msg.attach(MIMEText(file_get_content(mail_body),_subtype='html',_charset='utf8'))
    # 邮件附件
    att = MIMEText(file_get_content(mail_att), 'base64', 'utf-8')
    att.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', 'report.html'))
    msg.attach(att)
    try:
        s = smtplib.SMTP_SSL(host=mail_host,port=465)
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(me, mail_to, msg.as_string())
        s.close()
        print('send mail success!')
    except Exception as e:
        print(e)

    结语

    发邮件并不是什么困难的事儿,只是邮件涉及一堆参数,主机地址,用户名,密码啥的,把这些东西放在配置项里是好习惯.

    此文转载文,著作权归作者所有,如有侵权联系小编删除!

    原文地址:https://www.tuicool.com/articles/yuu6Z3a

    需要源码的 点击这里获取源码

  • 相关阅读:
    【逆序对】N*M Puzzle / Simple Puzzle
    【逆序对】Ultra
    bzoj 1814 Fornula 1
    hdu 1693 插头dp入门
    bzoj 2154
    没有上司的舞会
    【HNOI】合唱队
    luogu 自适应Simpson2
    luogu 自适应Simpson1
    【bzoj 1502】月下柠檬树
  • 原文地址:https://www.cnblogs.com/wxys/p/13769854.html
Copyright © 2020-2023  润新知