Python--自动发送邮件

214 阅读1分钟

Python--自动发送邮件

author wearmheart

使用python自动发邮件

下面先展示 python 如何3行代码 优雅的发送邮件。

import
smtps = yagmail.SMTP(user='your@sina.com', password='密钥', host='SMTP服务器')  # 建立连接
smtps.send(to="123456@qq.com", subject="标题", contents="正文")

yagmail 介绍

github仓库github.com/kootenpv/ya…

  • yagmail -- Yet Another GMAIL/SMTP client:
  • 译文:yagmail— 你的另一个GMAIL/SMTP客户端。

yagmail— 你的另一个GMAIL/SMTP客户端

准备工作

建议使用 conda 环境

准备工作

1.安装 yagmail

$ pip install yagmail

2.获取SMTP和密钥

这里以新浪邮箱为例,登录成功后进入设置页面,点击客户端pop/imap/smtp分类栏,会看见IMAP4服务/SMTP服务, SMTP就是客户端设置下SMTP服务器的值,密钥的话在你开启服务状态成功后会弹出(如果原本就是开启状态,需先关闭后再开启)。

新浪邮箱

发邮件

简单 Demo

import
smtps = yagmail.SMTP(user='your@sina.com', password='密钥', host='SMTP服务器')  # 建立连接
smtps.send(to="3534800157@qq.com", subject="标题测试", contents="正文",attachments='file.txt')
  • to:指定接收人的邮箱,可以是列表发送给多人
  • subject:邮件标题
  • contents:邮件正文内容
  • attachments: 附件 ,可以是列表,携带多个附件

附件拓展代码

import yaml 
import yagmail

class EmailData:
    def __init__(self,email_title,email_content,email_attachments):
        self.email_title = email_title
        self.email_content = email_content
        self.email_attachments = email_attachments
        
    def __call__(self, yag_serve,email_to):
        response = yag_serve.send(email_to,self.email_title,self.email_content,self.email_attachments)
        return response

def main():
    # 0.加载配置文件
    with open('./config.yaml',mode='r') as fp:
        cfg = yaml.safe_load(fp)
    # 1.建立链接 password:密钥值,不是邮箱密码
    yag_server = yagmail.SMTP(user=cfg['user'],password=cfg['password'],host=cfg['host'])
    # 2.构建发送数据
    x = EmailData('测试报告','这是测试的内容','./config.yaml')
    # 3.发送数据
    x(yag_server,'3534800157@qq.com')
    # 4.关闭链接
    yag_server.close()

if __name__=='__main__':
    main()

更多相关文章关注公众号: mp.weixin.qq.com/s?__biz=Mzk…

Reference