美文网首页
python群发邮件

python群发邮件

作者: 阿登20 | 来源:发表于2020-10-26 01:43 被阅读0次

    python发送邮件

    python_发送邮件.png
    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    """
    ===========================
    # @Time : 2020/10/25 16:14
    # @File  : send_email_02.py
    # @Author: adeng
    # @Date  : 2020/10/25
    ============================
    
    """
    
    
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    from email.mime.application import MIMEApplication
    from email.header import Header
    
    # 设置smtplib所需的参数
    # 下面的发件人,收件人是用于邮件传输的。
    smtpserver = 'smtp.163.com'
    username = 'XXX@163.com'
    password = 'XXX'
    sender = 'XXX@163.com'
    # receiver='XXX@126.com'
    # 收件人为多个收件人
    receiver = ['XXX@126.com', 'XXX@126.com']
    
    subject = 'Python email test'
    # 通过Header对象编码的文本,包含utf-8编码信息和Base64编码信息。以下中文名测试ok
    # subject = '中文标题'
    # subject=Header(subject, 'utf-8').encode()
    
    # 构造邮件对象MIMEMultipart对象
    # 下面的主题,发件人,收件人,日期是显示在邮件页面上的。
    msg = MIMEMultipart('mixed')
    msg['Subject'] = subject
    msg['From'] = 'XXX@163.com <XXX@163.com>'
    # msg['To'] = 'XXX@126.com'
    # 收件人为多个收件人,通过join将列表转换为以;为间隔的字符串
    msg['To'] = ";".join(receiver)
    # msg['Date']='2012-3-16'
    
    # 构造文字内容
    text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com"
    text_plain = MIMEText(text, 'plain', 'utf-8')
    msg.attach(text_plain)
    
    # 构造图片链接
    sendimagefile = open(r'D:\pythontest\testimage.png', 'rb').read()
    image = MIMEImage(sendimagefile)
    image.add_header('Content-ID', '<image1>')
    image["Content-Disposition"] = 'attachment; filename="testimage.png"'
    msg.attach(image)
    
    # 构造html
    # 发送正文中的图片:由于包含未被许可的信息,网易邮箱定义为垃圾邮件,报554 DT:SPM :<p><img src="cid:image1"></p>
    html = """
    <html>  
      <head></head>  
      <body>  
        <p>Hi!<br>  
           How are you?<br>  
           Here is the <a href="http://www.baidu.com">link</a> you wanted.<br> 
        </p> 
      </body>  
    </html>  
    """
    text_html = MIMEText(html, 'html', 'utf-8')
    text_html["Content-Disposition"] = 'attachment; filename="texthtml.html"'
    msg.attach(text_html)
    
    # 构造附件
    sendfile = open(r'D:\pythontest\1111.txt', 'rb').read()
    text_att = MIMEText(sendfile, 'base64', 'utf-8')
    text_att["Content-Type"] = 'application/octet-stream'
    # 以下附件可以重命名成aaa.txt
    # text_att["Content-Disposition"] = 'attachment; filename="aaa.txt"'
    # 另一种实现方式
    text_att.add_header('Content-Disposition', 'attachment', filename='aaa.txt')
    # 以下中文测试不ok
    # text_att["Content-Disposition"] = u'attachment; filename="中文附件.txt"'.decode('utf-8')
    msg.attach(text_att)
    
    # 发送邮件
    smtp = smtplib.SMTP()
    smtp.connect('smtp.163.com')
    # 我们用set_debuglevel(1)就可以打印出和SMTP服务器交互的所有信息。
    # smtp.set_debuglevel(1)
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()
    

    发送一个普通文本邮件

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    """
    ===========================
    # @Time : 2020/10/25 19:24
    # @File  : send_email_03_实战.py
    # @Author: adeng
    # @Date  : 2020/10/25
    ============================
    """
    
    from datetime import datetime
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    from email.mime.application import MIMEApplication
    
    
    #------------------------数据准备---------------
    # -----发送方----
    sender = "17740xxxx@qq.com"
    #授权码
    pwd = "mgoiscepuymaxxxx"
    
    
    # ---------接受方----------
    receiver = ["33052xxxx@qq.com","1774xxxxx@qq.com"]
    
    
    # 1 发送普通文本
    text = "阿登哥好帅"
    text_plain = MIMEText(text, "plain", "utf-8")
    
    #----------- 添加 主题,发件人,收件人,时间-----------------
    # 我们必须把Subject,From,To,Date添加到MIMEText对象或者MIMEMultipart对象中,
    # 邮件中才会显示主题,发件人,收件人,时间(若无时间,就默认一般为当前时间,该值一般不设置)
    
    msg = MIMEMultipart('mixed')
    msg['Subject'] = '---果芽测试好屌---'
    msg['From'] = '{} <{}>'.format("阿登",sender)
    msg['To'] = ";".join(receiver)
    msg['Date'] = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
    msg.attach(text_plain)
    
    # -----------发送邮件----------------
    
    
    try:
        smtp = smtplib.SMTP('smtp.qq.com', port=25)
        # smtp = smtplib.SMTP('smtp.163.com', port=25)
        smtp.login(sender, pwd)
        smtp.sendmail(sender, receiver, msg.as_string())
    except Exception as e:
            print('SMTP Exception:\n' + str(e) + '\n')
    finally:
        smtp.quit()
    
    

    参数化--读取yaml配置文件

    yaml配置文件

    sender:
      17740808xx@qq.com: [阿登xx,mgoiscepuymacxx]
      330524xxx@qq.com: [xxx君,owfggrvbddgpxxxx]
    
    receiver: [330524xxx@qq.com,17740xxxx@qq.com]
    
    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    """
    ===========================
    # @Time : 2020/10/25 22:28
    # @File  : send_email_04.py
    # @Author: adeng
    # @Date  : 2020/10/25
    ============================
    """
    
    from datetime import datetime
    import yaml
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    from email.mime.application import MIMEApplication
    
    # ------加载conf/emailconf.yaml 数据----
    with open(r"../conf/emailconf.yaml", "r") as f:
        datas = yaml.load(f,Loader=yaml.FullLoader) # Loader=yaml.FullLoader 去除警告
        print(datas)
    
    #------------------------数据准备---------------
    # -----发送方----
    sender = "1774080xxx@qq.com" # 每次发送方是不固定的,所以这里直接输入进去,通过邮件名获取测试人员名字
    #授权码
    
    pwd = datas["sender"][sender][1]
    
    # ---------接受方----------
    
    receiver = datas["receiver"]
    
    # 1 发送普通文本
    text = "阿登哥好帅"
    text_plain = MIMEText(text, "plain", "utf-8")
    
    #----------- 添加 主题,发件人,收件人,时间-----------------
    # 我们必须把Subject,From,To,Date添加到MIMEText对象或者MIMEMultipart对象中,
    # 邮件中才会显示主题,发件人,收件人,时间(若无时间,就默认一般为当前时间,该值一般不设置)
    
    msg = MIMEMultipart('mixed')
    msg['Subject'] = '---果芽测试好屌---'
    msg['From'] = '{0} <{1}>'.format(datas["sender"][sender][0],sender)
    msg['To'] = ";".join(receiver)
    msg['Date'] = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
    msg.attach(text_plain)
    
    # -----------发送邮件----------------
    
    
    try:
        smtp = smtplib.SMTP('smtp.qq.com', port=25)
        # smtp = smtplib.SMTP('smtp.163.com', port=25)
        smtp.login(sender, pwd)
        smtp.sendmail(sender, receiver, msg.as_string())
    except Exception as e:
            print('SMTP Exception:\n' + str(e) + '\n')
    finally:
        smtp.quit()
    
    
    

    打包发送带附件的邮件

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    """
    ===========================
    # @Time : 2020/10/25 23:03
    # @File  : send_email_05_带附件的邮件.py
    # @Author: adeng
    # @Date  : 2020/10/25
    ============================
    """
    
    from datetime import datetime
    import os
    import yaml
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    from email.mime.application import MIMEApplication
    from scripts.handle_file import HandleFile   # 调用zip打包方法
    
    # ------加载conf/emailconf.yaml 数据----
    with open(r"../conf/emailconf.yaml", "r") as f:
        datas = yaml.load(f,Loader=yaml.FullLoader) # Loader=yaml.FullLoader 去除警告
        print(datas)
    
    #------------------------数据准备---------------
    # -----发送方----
    sender = "17740xxxx@qq.com"
    #授权码
    
    pwd = datas["sender"][sender][1]
    
    # ---------接受方----------
    
    receiver = datas["receiver"]
    
    # 1. 发送普通文本
    text = "阿登哥好帅"
    text_plain = MIMEText(text, "plain", "utf-8")
    
    # 2.发送html文本
    html = """
    <html>  
      <head></head>  
      <body>  
        <p>Hi!<br>  
           How are you?<br>  
           Here is the <a href="http://www.baidu.com">link</a> you wanted.<br> 
        </p> 
      </body>  
    </html>  
    """
    text_html = MIMEText(html, "html", "utf-8")
    
    # 3. 发送图片
    image_file = r"pycharm_win快捷键.png"
    image_info = MIMEImage(open(image_file, "rb").read(), image_file.rsplit(".", 1)[-1])
    # 添加附件声明
    image_info.add_header('Content-Disposition', 'attachment', filename=os.path.basename(image_file))
    
    # 4. 添加PDF 邮件
    pdf_file = r"Python时间使用指南-V1.0.pdf"
    pdf_info = MIMEApplication(open(pdf_file, "rb").read()) # 和上面比少了1个参数,这里只能一个
    pdf_info.add_header('Content-Disposition', 'attachment', filename=os.path.basename(pdf_file))
    
    # 5. 发送zip包邮件--这里可以把report下面的文件打包
    
    zip_file = r"Python时间使用指南.zip"
    att_zip = MIMEText(open(zip_file,"rb").read(),'base64','utf-8')
    att_zip.add_header('Content-Disposition', 'attachment', filename=os.path.basename(zip_file))
    
    zip_file1 = r"f1.zip"
    att_zip1 = MIMEText(open(zip_file1,"rb").read(),'base64','utf-8')
    att_zip1.add_header('Content-Disposition', 'attachment', filename=os.path.basename(zip_file1))
    
    # 将一个文件夹打包之后,发送邮件.把当面目录所有文件打包为aaa.zip存放在当前目录,返回路径
    #用 MIMEText处理因为是文件所以已rb打开,第2个参数用 base64
    zip_package = HandleFile.make_package(r"aaa", "zip", os.path.dirname(__file__))
    zip_info1 = MIMEText(open(zip_package, "rb").read(), "base64", "utf-8")
    zip_info1.add_header('Content-Disposition', 'attachment', filename=os.path.basename(zip_package))
    
    # 6. 发送.txt文件
    text_file = r'adeng188.txt'
    text_info = MIMEApplication(open(text_file, "rb").read())
    text_info.add_header('Content-Disposition', 'attachment', filename=os.path.basename(text_file))
    #----------- 添加 主题,发件人,收件人,时间-----------------
    # 我们必须把Subject,From,To,Date添加到MIMEText对象或者MIMEMultipart对象中,
    # 邮件中才会显示主题,发件人,收件人,时间(若无时间,就默认一般为当前时间,该值一般不设置)
    
    msg = MIMEMultipart('mixed')
    msg['Subject'] = '---果芽测试好屌---'
    msg['From'] = '{0} <{1}>'.format(datas["sender"][sender][0],sender)
    msg['To'] = ";".join(receiver)
    msg['Date'] = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
    
    # 将所有类型的邮件添加到msg
    msg.attach(text_plain)
    msg.attach(text_html)
    msg.attach(image_info)
    msg.attach(pdf_info)
    msg.attach(text_info)
    msg.attach(att_zip)
    msg.attach(att_zip1)
    msg.attach(zip_info1)
    
    # -----------发送邮件----------------
    
    
    try:
        smtp = smtplib.SMTP('smtp.qq.com', port=25)
        # smtp = smtplib.SMTP('smtp.163.com', port=25)
        smtp.login(sender, pwd)
        smtp.sendmail(sender, receiver, msg.as_string())
    except Exception as e:
            print('SMTP Exception:\n' + str(e) + '\n')
    finally:
        smtp.quit()
        print("发送邮件成功")
    
    

    相关文章

      网友评论

          本文标题:python群发邮件

          本文链接:https://www.haomeiwen.com/subject/dwvomktx.html