python - yagmail 发送邮件

前言:

以前写过一篇使用smtplib发送邮件的文章
https://www.cnblogs.com/wwho/p/8609631.html


使用 yagmail 模块发送邮件更加简单,四行代码
以下是官方文档: https://github.com/kootenpv/yagmail


使用前先要安装 yagmail

pip install yagmail -i https://pypi.douban.com/simple

例子:简单发送邮件

# -*- coding:utf-8 -*-
import yagmail
# 链接邮箱服务器
yag = yagmail.SMTP( user="157540957@qq.com", password="授权码", host='smtp.qq.com')
"""
user:      发送的邮箱
password: 授权码
"""

# 邮箱正文
contents = ['测试发送邮件']

# 发送邮件
yag.send(to = '3437871062@qq.com', subject='subject', contents = contents, attachments=None)
"""
to : 接收者
subject : 邮件主题
contents: 正文
attachments: 附件
"""
yag.close()
print("邮件发送成功")

发送邮件给多个人

邮件发送给多个人,将接受的邮箱放在列表中即可


# 发送邮件
yag.send(to = ['3437871062@qq.com','2222@qq.com', '333@qq.com'], subject='subject', contents = contents, attachments="")


发送邮件带附件

# -*- coding:utf-8 -*-
import yagmail

yag = yagmail.SMTP( user="157540957@qq.com",
                    password="kayzilfyziulbhbb1",
                    host='smtp.qq.com')
"""
user:      发送的邮箱
password: 授权码
"""
# 邮箱正文
contents = ['测试发送邮件']
# 附件
attachments = "D:\\code\\0906\\api_test009\\report\\report.html"
# 发送邮件
try:
    yag.send(to = '3437871062@qq.com',
             subject='subject',
             contents = contents,
             attachments=attachments)

except Exception as e :
    print("Error: 抱歉!发送邮件失败。", e)
"""
to : 接收者
subject : 邮件主题
contents: 正文
attachments: 附件
"""

yag.close()



封装


# -*- coding:utf-8 -*-
import yagmail


def send(user, password, receiver):
    yag = yagmail.SMTP( user=user,
                        password=password,
                        host='smtp.qq.com')
    """
    user:      发送的邮箱
    password: 授权码
    """
    # 邮箱正文
    contents = ['测试发送邮件']
    # 附件
    attachments = "D:\\code\\0906\\api_test009\\report\\report.html"
    # 发送邮件
    try:
        yag.send(to=receiver,
                 subject='subject',
                 contents = contents,
                 attachments=attachments)

    except Exception as e :
        print("Error: 抱歉!发送邮件失败。", e)
    """
    to : 接收者
    subject : 邮件主题
    contents: 正文
    attachments: 附件
    """

    yag.close()


if __name__ == '__main__':
    send("157540957@qq.com", "kayzilfyziulbhbb1", "3437871062@qq.com")

------分界线------

勤则百病消除,从现在开始努力,最差的结果也是大器晚成而已,不慌!
posted @ 2021-10-20 14:33  西瓜_皮  阅读(756)  评论(0编辑  收藏  举报