MIME 附件不会与主题行一起发送

MIME Attachments won't send with Subject Line

我在发送带有附件和主题行的电子邮件时遇到了一些代码问题。

# Code exerpt from Oli:     
# Emails aren't sending with a subject--need to fix this.
def send_mail(self, send_from, send_to, subject, text, files=None, server="localhost"):
    assert isinstance(send_to, list)

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

    msg.attach(MIMEText(text))

    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)
            ))

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

此代码可以正常发送电子邮件,但它不会分隔 'Subject' 行,并且它发送的电子邮件的主题行为“NO SUBJECT”。这是我打印 MIME 消息的第一部分时显示的内容:

From nobody Thu Oct 29 16:17:38 2015
Content-Type: multipart/mixed; date="Thu, 29 Oct 2015 16:17:38 +0000";
to="me@email.com";
from="someserver@somewhere.com"; subject="TESTING";
boundary="===============0622475305469306134=="
MIME-Version: 1.0

--===============0622475305469306134==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

Here we go, oh! ho! ho!
--===============0622475305469306134==
Content-Type: application/octet-stream; Content-  Disposition="attachment;
filename=\"Log_Mill.py\""; Name="Log_Mill.py"
MIME-Version: 1.0
Content-Transfer-Encoding: base64

如果我连续几个小时不插电,我也许能解决这个问题,但我希望避免为这种微不足道的修复做额外的工作。

感谢任何帮助!

您还可以使用专门用于编写 HTML 电子邮件、内联显示图片和轻松附加文件的软件包!

我指的包是 yagmail 而我是 developer/maintainer.

import yagmail
yag = yagmail.SMTP('email@email.com', 'email_pwd')
file_names = ['/local/path/f.mp3', '/local/path/f.txt', '/local/path/f.avi']
yag.send('to@email.com', 'Sample subject', contents = ['This is text'] + filenames)

仅此而已。

使用 pip install yagmail 获取您的副本。

内容可以是一个列表,您还可以在其中添加文本,您只能将 file_names 作为内容,太棒了不是吗?

它读取文件,神奇地确定编码,并附上它:)

阅读 github 了解其他技巧,例如无密码脚本、别名等等。

您将主题等指定为多部分容器的属性,但这是不正确的。您要指定的 headers 应该作为 headers 传递给 msg 本身,如下所示:

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

输出应该更像

From nobody Thu Oct 29 16:17:38 2015
Date: Thu, 29 Oct 2015 16:17:38 +0000
To: <me@email.com>
From: <someserver@somewhere.com>
Subject: TESTING
Content-Type: multipart/mixed; 
   boundary="===============0622475305469306134=="
MIME-Version: 1.0

--===============0622475305469306134==
Content-Type: text/plain; .......