我在发送带有附件和主题行的电子邮件时遇到了一些代码问题。
# 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()
这个代码发送一封电子邮件罚款,但它没有取消"主题"行,它发送的电子邮件的主题行为"无主题"。以下是我打印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
如果我坚持几个小时,我可能会想出来,但我希望避免为这样一个琐碎的解决方案付出额外的工作。
感谢您的帮助!
您将Subject等指定为多部分容器的属性,但这是不正确的。要指定的头应该作为头传递给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; .......
您还可以使用专门用于编写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了解其他技巧,如无密码脚本、别名等等。