当前位置:主页 > 软件编程 > Python代码 >

python 中使用yagmail 发送邮件功能

时间:2022-06-23 11:39:21 | 栏目:Python代码 | 点击:

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("123456@qq.com",
              "gwheybuaamrqbihh",
              'smtp.qq.com',
              "邮件正文内容",
              "123456@qq.com",
              "E:\\proto_code\\Roshan-01-microscript-proto_test-master-src\\src\\report\\report.html")

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

# 发送邮件
yag.send(to = ['123456@qq.com','678910@qq.com', '10111213@qq.com'], subject='subject', contents = contents, attachments="")

4.发送邮件带附件

# -*- 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()

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:\\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("123456@qq.com", "kayzilfyziulbhbb1", "45678910@qq.com")

您可能感兴趣的文章:

相关文章