python使用MIMEMultipart发送多个附件的邮件

python2.3以及更高版本默认自带smtplib模块,无需额外安装。邮件传输文本,邮件主题会包含HTML、图像、声音以及附件等。

email.mime可以理解为smtplib模块邮件内容主体的扩展,从只支持纯文本格式扩展到HTML,同时支持附件、音频、图像等格式,smtplib只负责邮件的投递
SMTP类的定义:
smtplib.SMTP():构造函数,功能是与smtp服务器建立连接,连接成功后,就可以向服务器发送相关请求,比如登录,校验,发送,退出
SMPT.connect():

EMAIL类:
email.mime.multipart.MIMEMultipart([_subtype[,boundary]]):生成包括多个部分的邮件体
email.mime.image.MIMEImage():创建包含音频数据的邮件体
from email.mime.text import MIMEText

#!/usr/bin/python
#coding=utf8
#Name:  py_sendattach.py        
#Purpose:       send ptp data to antifraud
#Author:        yangshuqiang

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

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

        msg.attach(msgtext)

        os.chdir(path)  
        dir = os.getcwd()
        
        for fn in os.listdir(dir): ##返回字符串文件名   
                print fn
                attach = MIMEText(open(fn,'rb').read()) 
                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()
                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, e:
                print "失败"+str(e)

if __name__=='__main__':
        msg = addAttch('[email protected]', '对账', '对账数据', '/home/dbaops/Shell/finance_debt/AccountBalance')
        sendMail(msg)







 
 

你可能感兴趣的:(python之路,python发多个附件的邮件,MIMEMultipart,MIMEText)