Github 大牛封装 Python 代

发布时间:2019-05-18 23:56:29编辑:auto阅读(2329)

    *注意:全文代码可左右滑动观看

    在运维开发中,使用 Python 发送邮件是一个非常常见的应用场景。今天一起来探讨一下,GitHub 的大牛门是如何使用 Python 封装发送邮件代码的。

    一般发邮件方法

    SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。

    我们以前在通过Python实现自动化邮件功能的时候是这样的:

     1 import smtplib
     2 from email.mime.text import MIMEText
     3 from email.header import Header
     4 #发送邮件服务器
     5 smtpserver = 'smtp. sina. com'
     6 #发送邮件用户/密码
     7 user = 'usernamee@sina. com'
     8 password = '123456'
     9 #发送邮件 python学习群984632579
    10 sender = 'username@sina. com"
    11 #接收邮件
    12 receiver = 'receive@126. com'
    13 #发送邮件主题
    14 subject = 'Python email test'
    15 #编写HTML类型的邮件正文
    16 msg = MIMEText('<html><h1>你好 ! </h1></html>','html','utf-8')
    17 msg['Subject'] = Header(subject,'utf-8')
    18 #连接发送邮件
    19 smtp = smtplib.SMTP()
    20 smtp.connect(smtpserver)
    21 smtp.login(user,password)
    22 satp.sendmail(sender, receiver, msg.as_ string())
    23 satp.quit()

     

    python发邮件需要掌握两个模块的用法,smtplib和email,这俩模块是python自带的,只需import即可使用。smtplib模块主要负责发送邮件,email模块主要负责构造邮件。

    smtplib模块主要负责发送邮件:是一个发送邮件的动作,连接邮箱服务器,登录邮箱,发送邮件(有发件人,收信人,邮件内容)。

    email模块主要负责构造邮件:指的是邮箱页面显示的一些构造,如发件人,收件人,主题,正文,附件等。

    其实,这段代码也并不复杂,只要你理解使用过邮箱发送邮件,那么以下问题是你必须要考虑的:

    • 你登录的邮箱帐号/密码
    • 对方的邮箱帐号
    • 邮件内容(标题,正文,附件)
    • 邮箱服务器(SMTP.xxx.com/pop3.xxx.com)

    如果要把一个图片嵌入到邮件正文中怎么做?直接在HTML邮件中链接图片地址行不行?答案是,大部分邮件服务商都会自动屏蔽带有外链的图片,因为不知道这些链接是否指向恶意网站。

    要把图片嵌入到邮件正文中,我们只需按照发送附件的方式,先把邮件作为附件添加进去,然后,在HTML中通过引用src="cid:0"就可以把附件作为图片嵌入了。如果有多个图片,给它们依次编号,然后引用不同的cid:x即可。

    yagmail 实现发邮件

    yagmail 可以更简单的来实现自动发邮件功能。

    github项目地址: https://github.com/kootenpv/yagmail

    代码开源,解释如下:

    1 yag = SMTP(args.user,args.password)
    2 yag.send(to.=args.to,subject=args.subject,contents=args.contents,attachments=args.attachments)

     

    安装:

    pip install yagmail

     

    简单例子:

    import yagmail
    #链接邮件服务器
    yag = yagmail.SMTP(user="user@126.com",password="1234",host='smtp.126.com')
    #邮件正文
    contents = [‘This is the body,and here is just text http://somedomain/image.png','You can find an andio file atteched.','/local/path/song mp3']
    #发送邮件
    yag.send('taaa@126.com','subject',contents)

     

    给多个用户发邮件:

    只需要将接收邮箱 变成一个list即可。

    yag.send(['aa@126.com','bb@qq.com','cc@gmail.com'], 'subject', contents)

     

    发送附件

    如何发送附件呢?只要添加一个附件列表就可以了。

    yag.send('aaaa@126.com', '发送附件', contents, ["d://log.txt","d://baidu_img.jpg"])

     

    抄送

    #邮件正文 文本及附件contents = ['This is the body,and here is just text http://somedomain/image.png','You can find an audio file attached.','/local/path/song.mp3','测试邮件','test.html','logo.jpg','yagmal_test.txt']#发送yag.send(to='xx@xx.com',cc='xxx@xxx.com',subject='发送附件',contend=contents)

     

    很简单吧,开箱即用~~

关键字

上一篇: CRM之分页

下一篇: python爬虫(六)