Python第三方库—yagmail

 

简述

yagmail是Python的基于GMAIL / SMTP客户端的第三方库,旨在简单发送邮件
使用前应先安装

三行代码发QQ邮件

import yagmail
yag=yagmail.SMTP(user='3079****95@qq.com',password='nm************hd',host='smtp.qq.com')
yag.send(to='3580****14@qq.com',subject='practice',contents='my first yagmail exercise')

第一行导入yagmail库
第二行通过yagmail.SMTP()创建yagmail对象:user是自己的邮箱,password是自己QQ邮箱的密钥,host是smtp针对qq的服务器域名
第三行to是发送对象,subject是主题,contents是正文内容

用法

1. 导入yagmail

import yagmail

2. 建立对象连接

yag=yagmail.SMTP(user='',password='',host='')

QQ邮箱获取密钥方式

打开QQ邮箱,设置–账户–开启SMTP服务
在这里插入图片描述
然后按要求发送短信验证即可
在这里插入图片描述

3. 发送邮件

yag.send()

send中有多种参数可选,如下列出:

参数

  • to
    用来指定发送的对象即收件人,传递字符串格式yag.send(to='objname@mail.com')
    当指定多个发送对象时,可以用列表或元组的形式,如yag.send(to=['3577****11@qq.com','wei*******dj@163.com'])
    如果要对电子邮件地址提供别名,可以用字典形式:

    recipients={'mike@xxx.com':'MIKE','mary@xxx.com':'MARY'}
    yag.send(to=recipients)
  • subject
    邮件主题yag.send(subject='主题')

  • contents
    邮件内容,即正文。一般为字符串,可用列表传递多个内容yag.send(contents=['正文1','正文2'])

  • attachments
    附件yag.send(attachments='C://Users//86135//Desktop//python.txt')有多个附件时用列表

  • cc
    抄送邮件,将邮件同时发送给收件人以外的人yag.send(cc='xxx@mail.com')

  • bcc
    密送,与抄送不同的是收件人看不到其他人的邮箱地址

  • preview_only
    布尔型,表示仅预览,可以发送但对方收不到

  • header
    头部信息,传递字典参数

示例

import yagmail
import time

yag=yagmail.SMTP(user='30******95@qq.com',password='nm************hd',host='smtp.qq.com')
start=time.time()

yag.send(to='35******14@qq.com',subject='python',contents='python file',
         attachments='C://Users//86135//Desktop//python.txt')
end=time.time()

print("成功发送,耗时{:.2f}s".format(end-start))

结果:
在这里插入图片描述

 
posted @ 2022-10-26 11:44  weer-wmq  阅读(93)  评论(0编辑  收藏  举报