zoukankan      html  css  js  c++  java
  • 接口测试基础——第2篇smtplib发送带附件的邮件

    我先给大家补充一个用QQ发送纯文本电子邮件的代码,用QQ的朋友可以参考一下:

    # coding=utf-8  
    import smtplib
    from email.mime.text import MIMEText
    mail_host = “smtp.qq.com”
    receivers = “123@qq.com”
    sender = “456@qq.com”
    passwd = ‘QQ邮箱的授权码’
    contents = “python发送邮件”
    # 构造邮件正文
    msg=MIMEText(contents,”plain”,”utf-8”)
    # 构造邮件头部
    msg[“From”]=sender
    msg[“To”]=receivers
    msg[“Subject”] = “主题”
    try:
    server = smtplib.SMTP_SSL(mail_host, 465)
    server.login(sender, passwd)
    server.sendmail(sender, receivers, msg.as_string())
    print “发送成功”
    except smtplib.SMTPException:
    print “无法发送”

    今天我们要写的代码是发送带附件的电子邮件:

    
    # coding: utf-8
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    sender = '你的邮箱@163.com'
    passwd = '授权码'
    receivers = ['123@qq.com','456@qq.com']
    receiver = ','.join(receivers)
    mail_host = 'smtp.163.com'
    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = receiver
    msg['Subject'] = 'Python test'
    # 邮件正文
    msg.attach(MIMEText('sending email test', 'plain', 'utf-8'))
    # 构造附件1
    att1 = MIMEText(open('文件的路径比如:C:\Users\lenovo\Desktop\a.txt', 'rb').read(), 'base64', 'utf-8')
    att1['Content-Type'] = 'application/octet-stream'
    att1['Content-Disposition'] = 'attachment; filename= "a.txt"' msg.attach(att1)
    # 构造附件
    att2 = MIMEText(open('文件的路径比如:C:\Users\lenovo\Desktop\b.txt').read(), 'base64', 'utf-8')
    att2['Content-Type'] = 'application/octet-stream'
    att2['Content-Disposition'] = 'attachment; filename="b.txt"' msg.attach(att2)
    try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)
    smtpObj.login(sender, passwd)
    smtpObj.sendmail(sender, receiver, msg.as_string())
    print 'Success'
    except smtplib.SMTPException:
    print 'Error'

    运行以后就可以收到带有附件的电子邮件了。

    如果不明白,就多谢两遍

    微信公众号搜索“自动化测试实战”或扫描下方二维码添加关注~~~

  • 相关阅读:
    hdu1852 Beijing 2008
    hdu-2582 f(n)---找规律+素数筛法
    hdu-1452 Happy 2004---因子和+逆元
    LightOJ-1028 Trailing Zeroes (I)---因子数目
    hdu1215 七夕节---因子和
    因子和&&因子数
    hdu-1492 The number of divisors(约数) about Humble Numbers---因子数公式
    hdu-2136 Largest prime factor---巧用素数筛法
    欧拉函数
    BZOJ4418: [Shoi2013]扇形面积并
  • 原文地址:https://www.cnblogs.com/captainmeng/p/7682069.html
Copyright © 2011-2022 走看看