• Python自动发邮件


    本文来自:虫师

    一般发邮件方法smtplib

     1 import smtplib
     2 from email.mine.text import MINEText
     3 from email.header import Header
     4 
     5 # 发送邮箱服务器
     6 smtpserver = 'stmp.sina.com'
     7 # 发送邮箱用户/密码
     8 user = 'username@sina.com'
     9 password = '123456'
    10 # 发送邮箱
    11 sender = 'username@sina.com'
    12 # 接收邮箱
    13 receiver = 'receiver@139.com'
    14 # 发送邮件主题
    15 subject = 'Python email test'
    16 
    17 # 编写HTML类型的邮件正文
    18 msg = MIMEText('<heml><hl>你好!</hl></html>', 'html', 'utf-8')
    19 msg['Subject'] = Header(subject, 'utf-8')
    20 
    21 # 连接发送邮件
    22 smtp = smtplib.SMTP()
    23 smtp.connect(smtpserver)
    24 smtp.login(user, password)
    25 smtp.sendmail(sender, receiver, msg.as_string())
    26 smtp.quit()

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

    • 你登录的邮箱账号/密码
    • 对方邮箱账号
    • 邮件内容(标题,正文,附件)
    • 邮箱服务器

    yagmail实现发邮件

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

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

    总共4行代码。

    给多个用户发送邮件:

    # 发送邮件
    yag.send(['aa@126.com', 'bb@qq.com', 'cc@gmail.com'], 'subject', contents)

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

    发送带附件的邮件:

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

    只需要添加要发送的附件列表即可。

  • 相关阅读:
    log4j日志格式化
    日志级别是如何工作?
    Java拦截过滤器模式
    js实现图片轮播
    js实现表格的增删改查
    企业外贸网站建设的要求及注意事项
    逛知乎才知网站建设不只有wordpress建站系统,小白值得收藏
    三款适用于企业建站的CMS建站系统
    前端开发常用的网站整理
    网站建设教程:虚拟主机如何安装PageAdmin建站系统
  • 原文地址:https://www.cnblogs.com/keye/p/8574426.html
Copyright © 2020-2023  润新知