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

时间:2015-10-29 16:27:02

标签: python email attachment mime

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

# Code exerpt from Oli:     http://stackoverflow.com/questions/3362600/how-to-send-email-attachments-with-python
# 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()

此代码发送的电子邮件很好,但它没有消除'主题'行和它发送的电子邮件的主题行为“#34; NO SUBJECT。”#39;这是我打印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

如果我连续几个小时都停下来,我或许可以弄明白,但我希望避免额外的工作来解决这个问题。

感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

您还可以使用专门用于编写HTML电子邮件的包,在线显示图片并轻松附加文件!

我指的是yagmail,我是开发人员/维护人员。

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以获取其他技巧,例如无密码脚本,别名以及其他技巧。

答案 1 :(得分:0)

您正在将主题等分配为多部分容器的属性,但这是不正确的。您要指定的标题应作为标题传递给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; .......