如何使用Python发送电子邮件附件

问题:

理解如何使用Python发送附件时遇到问题。我已成功通过smtplib发送简单的邮件。有人可以解释如何在电子邮件中发送附件。我知道在线还有其他帖子,但作为一个Python初学者,我觉得他们很难理解。

回答:

这是另一个,改编自here

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


def send_mail(send_from, send_to, subject, text, files=None,
              server="127.0.0.1"):
    assert isinstance(send_to, list)

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

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


    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()

它与第一个例子是一样的…但它应该更容易进入。

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: How to send email attachments with Python

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

40 − = 34