zoukankan      html  css  js  c++  java
  • python实现邮件循环自动发件

    发邮件是一种很常见的操作,本篇主要介绍一下如何用python实现自动发件。

    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.header import Header
    from email.mime.image import MIMEImage
    import time
    mail_host="smtp.126.com"
    mail_user="xxx@126.com"
    mail_pass="******"#注意如果邮箱开启了授权码,此处要填写授权码,否则会报smtplib.SMTPAuthenticationError: (535, b'Error: authentication failed')
    sender="xxx@126.com"
    receiver = ['邮箱1','邮箱2']#群发邮件
    for i in range(n):#自定义循环发多少遍
        try:
            message = MIMEMultipart()
            message["From"] = Header(sender)
            message["To"] = ','.join(receiver)
            message["Subject"] = Header("主题", "utf-8").encode()#主题
            message.attach(MIMEText("正文", "plain", "utf-8"))#正文
            """
            定附件
            """
            att = MIMEText(open(r'C:UsersAdministratorDesktop1.txt').read(), "base64", "utf-8")
            att["Content-Type"] = 'application/octet-stream'
                att.add_header("Content-Disposition", 'attachment', filename="1.txt")#这一步可避免文件不能正常打开
            message.attach(att)
            """
            构造图片(以附件形式上传)
            """
            image = MIMEImage(open(r'C:UsersAdministratorDesktop1.jpg', 'rb').read())
            image.add_header('Content-ID', '<image1>')#可避免图片不能正常打开
            image["Content-Disposition"] = 'attachment; filename="picture.jpg"'
            message.attach(image)
               """
               发送邮件
               """
            smtp = smtplib.SMTP_SSL(host=mail_host)
            smtp.connect(host=mail_host, port=465)
            smtp.login(mail_user, mail_pass)
            smtp.sendmail(sender, message['To'].split(','), message.as_string())
            print("在%s第" % ctime(), str(i+1), "封邮件发送")
            smtp.quit()
        except smtplib.SMTPException as e:
              raise e

    最终实现
    在这里插入图片描述

    本文首发于python黑洞网,博客园同步更新

  • 相关阅读:
    k8spod资源的基础管理操作
    k8s名称空间资源
    bzoj5011: [Jx2017]颜色
    bzoj5010: [Fjoi2017]矩阵填数
    bzoj5008: 方师傅的房子
    bzoj5007: TCP协议
    bzoj5003: 与链 5004: 开锁魔法II 5005:乒乓游戏
    bzoj5020: [THUWC 2017]在美妙的数学王国中畅游
    bzoj5006: [THUWC2017 Bipartite]随机二分图
    bzoj4480: [Jsoi2013]快乐的jyy
  • 原文地址:https://www.cnblogs.com/pythonzhilian/p/13650088.html
Copyright © 2011-2022 走看看