使用python一次性发送包含多个附件的邮件(即指定目录下)

# !/usr/bin/python
# coding=utf8

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import os
import sys

mail_host = 'smtp.qq.com'
mail_from = '[email protected]'
mail_pass = 'xxxxxxxxxxxxxxxxx'


def addAttch(to_list, subject, content, path):
    msg = MIMEMultipart('related')  # 采用related定义内嵌资源的邮件体
    # _subtype有plain,html等格式,避免使用错误
    msgtext = MIMEText(content, _subtype='plain', _charset='utf-8')

    msg.attach(msgtext)

    os.chdir(path)
    dir = os.getcwd()

    for fn in os.listdir(dir):  # 返回字符串文件名
        print(fn)
        attach = MIMEText(open(fn, 'rb').read(), 'plain', 'utf-8')
        attach["Content-Type"] = 'application/octet-stream'
        attach["Content-Disposition"] = 'attachment; filename=' + fn
        msg.attach(attach)

    msg['Subject'] = subject
    msg['From'] = mail_from
    msg['To'] = to_list
    return msg


def sendMail(msg):
    try:
        server = smtplib.SMTP(mail_host)
        server.connect(mail_host, 587)
        server.starttls()
        server.login(mail_from, mail_pass)
        server.sendmail(mail_from, msg['To'], msg.as_string())
        server.quit()  # 断开smtp连接
        print("邮件发送成功")
    except Exception as e:
        print("失败" + str(e))


if __name__ == '__main__':
    msg = addAttch('[email protected]', 'pic', 'picture', 'D:\\壁纸test')
    sendMail(msg)

猜你喜欢

转载自blog.csdn.net/zyx_ly/article/details/88039300