网络编程 二 发送带附件的邮件

20180627
author: wills

发送电子邮件

在我的上一篇博客网络编程 一 发送邮件已经初步介绍python发送邮件的办法,但是我们往往有很多邮件是带有附件的,今天我介绍一个可以带有不同附件的写法

# 发送带有不同附件的邮件写法
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from smtplib import SMTP
from email.header import Header
from email.mime.text import MIMEText


def main():
    # 创建一个带附件的邮件消息对象
    message = MIMEMultipart()

    # 创建文本内容
    text_content = MIMEText('附件为本小组blog情况,以及美女图片,请查收', 'plain', 'utf-8')
    message['Subject'] = Header('本月数据', 'utf-8')
    # 将文本内容添加到邮件消息对象中
    message.attach(text_content)

    # 读取TXT文件并将文件作为附件添加到邮件消息对象中
    with open('hello.txt', 'rb') as f:
        txt = MIMEText(f.read(), 'base64', 'utf-8')
        txt['Content-Type'] = 'text/plain'
        txt['Content-Disposition'] = 'attachment; filename=hello.txt'
        message.attach(txt)
    # 读取XLSX文件并将文件作为附件添加到邮件消息对象中
    with open('齐心小队的blog.xlsx', 'rb') as f:
        xls = MIMEText(f.read(), 'base64', 'utf-8')
        xls['Content-Type'] = 'application/vnd.ms-excel'
        xls['Content-Disposition'] = 'attachment; filename=齐心小队的blog.xlsx'
        message.attach(xls)

    # 读取jpg图片,并且添加为附件
    # 这里是添加图片附件的方法,我注释掉是因为添加之后很容易会被
    # 网易163邮箱识别为垃圾邮件导致发送失败
    # with open('hello.jpg', 'rb') as f:
    #    img = MIMEApplication(f.read())
    #    img.add_header('Content-Disposition', 'attachment', filename='hello.jpg')
    #    message.attach(img)

    # 创建SMTP对象
    smtper = SMTP('smtp.163.com')
    # 开启安全连接
    smtper.starttls()
    sender = '[email protected]'
    receivers = ['[email protected]', '[email protected]']
    # 登录到SMTP服务器
    # 请注意此处不是使用密码而是 邮件客户端授权码 进行登录
    # 对此有疑问的读者可以联系自己使用的邮件服务器客服
    smtper.login(sender, 'xxxxxx')
    # 发送邮件
    smtper.sendmail(sender, receivers, message.as_string())
    # 与邮件服务器断开连接
    smtper.quit()
    print('发送完成!')


if __name__ == '__main__':
    main()

你可能感兴趣的:(python,网络编程,发邮件)