python发送邮件zmail库

第三方库“zmail”和“yagmail”可实现邮件发送。在实际使用对比zmail比yagmail更简洁。使用zmail,无需登录OA邮箱,便可完成邮件的发送及附件的自动加载。

import zmail


def send_zmail(sender, sender_password, addressee, host, port=465, inspect_smtp_pop=False):
    # 使用邮件服务商的邮箱,代码中的"password"要填写"授权码",也有叫邮件第三方客户端独立密码。
    # 同时出现content_text和content_html时,只显示content_html
    mes = {
        'subject': 'zmail库邮件测试',  # 主题
        'content_text': '邮件内容:\n这是第一段',  # 正文内容(纯文本形式)
        'content_html': r'<h1 style="color:red">一级标题</h1><a href="https://www.baidu.com"><h2 style="color:green">二级标题点击查看更多<<</h2><p></a><img src="D:\zhuomian\demo\tom.gif" alt="测试图片显示" title="牛牛牛" width="100" height="150"></p>',
        'attachments': [r'D:\zhuomian\test_file\学习培训导入.xlsx', r'D:\zhuomian\导入文件\批量导入模板.xlsx',
                        r'D:\zhuomian\test_file\345.txt'],  # 附件
    }
    try:
        server = zmail.server(username=sender, password=sender_password, smtp_host=host, pop_port=port)
        if inspect_smtp_pop:  # 测试SMTP/POP连接
            print('SMTP连接成功') if server.smtp_able() else print('SMTP连接失败')
            print('POP连接成功') if server.pop_able() else print('POP连接失败')
        try:
            server.send_mail(
                recipients=addressee,
                mail=mes,
                # cc='',   # 密送人员,列表或字符串
            )
        except Exception as e:
            print(f'发送失败:{e}')
    except Exception as e:
        print(f'登录失败:{e}')

猜你喜欢

转载自blog.csdn.net/JBY2020/article/details/131813016