美文网首页
Python邮件发送

Python邮件发送

作者: Volent | 来源:发表于2019-09-27 11:09 被阅读0次

使用Python发邮件常用的库有smtplib email等常用的,但是代码太复杂,不便于学习,zmail库更简单,可以快速上手

github地址https://github.com/ZYunH/zmail

安装

使用pip安装

> pip3 install zmail

功能

自动查找服务器地址及其端口。

自动使用合适的协议登录。

自动将python字典转换为MIME对象(带附件)。

自动添加邮件标题和本地名称,以避免服务器拒绝您的邮件。

轻松自定义邮件标题。

支持HTML作为邮件内容。

只需要python> = 3.5,您可以将其嵌入到项目中而无需其他模块。

代码演示

import zmail

import os

# 邮箱配置基本信息

mail_cof = {

    "sender": "xxx.x@ingeek.com",

    "psw": "xxxxxx",

    "smtp_host": "smtp.exmail.qq.com",

    "smtp_port": 465,

    "receiver": ['xxx.xx@ingeek.com', 'xx.x@ingeek.com']

}

cur_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))

# report_path是报告文件地址

report_path = os.path.join(cur_path, "report", "report.html")

def send_mail(sender, psw, smtp_host, smtp_port, receiver):

    '''

    发送html报告到邮箱

    :return:

    '''

    # open读取html内容

    with open(report_path, 'r', encoding="utf-8") as f:

        content_html = f.read()

    mail = {

        'subject': '接口测试报告', # Anything you want.

        # 'content_text': "主题:",  # Anything you want.

        'content_html':  content_html, # read html content

        'attachments': report_path, # Absolute path will be better.

    }

    try:

        server = zmail.server(sender,

                              psw,

                              smtp_host=smtp_host,

                              smtp_port=smtp_port)

        server.send_mail(receiver, mail)

        print('邮件发送成功!')

    except Exception as msg:

        print("邮件发送失败:%s " % str(msg))

if __name__ == '__main__':

    send_mail(**mail_cof)

发送HTML内容

with open('/Users/example.html','r') as f:

    content_html = f.read()

mail = {

    'subject': 'Success!', # Anything you want.

    'content_html': content_html,

    'attachments': '/Users/zyh/Documents/example.zip', # Absolute path will be better.

}

server.send_mail('yourfriend@example.com',mail)

使用抄送

server.send_mail(['foo@163.com','foo@126.com'],mail,cc=['bar@163.com'])

同样,你也可以命名它们(使用元组,首先是它的名字,下一个是它的地址)

server.send_mail(['foo@163.com','foo@126.com'],mail,cc=[('Boss','bar@163.com'),'bar@126.com'])

收邮件

更多功能参考

github地址https://github.com/ZYunH/zmail

相关文章

网友评论

      本文标题:Python邮件发送

      本文链接:https://www.haomeiwen.com/subject/vaiouctx.html