一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

python中使用yagmail发送邮件功能代码示例

时间:2022-06-25 01:28:56 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下python中使用yagmail发送邮件功能代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

1.使用前先要安装 yagmail

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

2.使用QQ邮箱发送邮件,使用的是授权码,需要先到QQ邮箱申请授权码。

邮箱设置-->账户

3.yagmail 模块发送邮件更加简单,四行代码

# -*- encoding: utf-8 -*-

import yagmail

def E_mali_jj(fr,key,etype,text,to,attachments):
    '''
    :param fr: 发送邮箱
    :param key: 授权码
    :param etype: 邮件类型
    :param text: 文本
    :param to: 接受邮箱
    :param attachments: 附件文件地址,空则填''
    :return:
    '''
   # 链接邮箱服务器
    yag=yagmail.SMTP(user=fr,password=key,host=etype)
    # 邮箱正文
    contents=[text]
    # 发送邮件
    yag.send(to=to,subject='邮件标题',contents=contents,
             attachments=attachments)   #subject 标题
    yag.close()
    print("邮件发送成功")

if __name__ == '__main__':
    E_mali_jj("[email protected]",
              "gwheybuaamrqbihh",
              'smtp.qq.com',
              "邮件正文内容",
              "[email protected]",
              "E:proto_codeRoshan-01-microscript-proto_test-master-srcsrcreportreport.html")

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

# 发送邮件
yag.send(to = ['[email protected]','[email protected]', '[email protected]'], subject='subject', contents = contents, attachments="")

4.发送邮件带附件

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

yag = yagmail.SMTP( user="[email protected]",
                    password="kayzilfyziulbhbb1",
                    host='smtp.qq.com')
"""
user:      发送的邮箱
password: 授权码
"""
# 邮箱正文
contents = ['测试发送邮件']
# 附件
attachments = "D:code906api_test009reportreport.html"
# 发送邮件
try:
    yag.send(to = '[email protected]',
             subject='subject',
             contents = contents,
             attachments=attachments)

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

yag.close()

5.封装

# -*- 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:code906api_test009reportreport.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("[email protected]", "kayzilfyziulbhbb1", "[email protected]")

热门栏目