欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python 发送邮件附件

程序员文章站 2022-07-01 12:11:41
...
import smtplib

from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate

mail_host=''
mail_user=''
mail_pass=''
mail_postfix='' 

def send_mail(to_list,sub,content,files=None): 
    me='' + '<' + mail_user + '@' + mail_postfix + '>' 
    text = MIMEText(content,_subtype='html',_charset='utf-8')
    
    msg = MIMEMultipart()
    msg.attach(text)
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = ';'.join(to_list)

    for f in files or []:
        with open(f, "rb") as fil:
            msg.attach(MIMEApplication(
                fil.read(),
                Content_Disposition='attachment; filename="%s"' % basename(f),
                Name=basename(f)
            ))

    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(me, to_list, msg.as_string())
        s.close()
        return True
    except Exception, e:
        print str(e)
        return False