使用 Python 的 email.mime.multipart 发送 HTML 邮件时命名内联图像

Naming inline images when sending HTML mails with Python's email.mime.multipart

使用 python 的电子邮件包,我发送带有内联图像的电子邮件。这样可行。现在,我想为这些图像分配实际名称(不是 html 标题 ..),因此在下载它们时它们不会被命名为 'noname'(例如 gmail) .现在的代码:

from email.mime.multipart import MIMEMultipart

msgRoot = MIMEMultipart('related')
msgAlternative = MIMEMultipart('alternative')
...

# image file
msgText = MIMEText('<img src="cid:image" alt="Smiley" title="title">', 'html')
msgAlternative.attach(msgText)

# In-line Image
with open('/Users/john/Desktop/2015-04-21_13.35.38.png', 'rb') as fp:
    msgImage = MIMEImage(fp.read())
msgImage.add_header('Content-ID', '<image>')
msgRoot.attach(msgImage)

...
server.sendmail(sender, recipients, msgRoot.as_string())

我试了很多东西,也问了很多次google。有可能吗?谢谢

你说的问题我查了一下,很难找!

经您验证,可以通过以下方式设置名称:

msgImage = MIMEImage(fp.read(), name = 'filename')

此外,我正在维护yagmail;一个应该可以轻松发送电子邮件的软件包。我包含了您想要的功能,并且刚刚发布了一个新的小更新!

您可以通过 pip install 获得 yagmail(或 pip3 install 获得 Python 3)。

开始连接:

import yagmail
yag = yagmail.Connect('username', 'password')

这只会发送图像:

yag.send('someone@mail.com', contents = ['/local/or/external/image.png'])

它将使用路径结尾的默认命名(在本例中为 image.png)。虽然也可以给一个别名(别名在任何地方都是由字典完成的,像这样:contents = [{'/local/or/external/image.png' : 'newfilename'}]

程序包会自己猜测文件内容,也就是说,它会知道你在说什么 HTML/images/other 类型的内容,或者什么时候在写文本......你都可以放入 contents!

另一个例子:

yag.send(to = 'someone@mail.com', subject = 'Demonstration',  
         contents = ['Hey buddy, have a look at the picture below:', '/local/image.png'])

它还有许多您可能会觉得有吸引力的其他功能,described and maintained here

解决方案:

实际上可以分配 Content-IDContent-TypeContent-Transfer-Encoding & Content-Disposition 到一个 MIME 文件 (check for more)。这样,您只需添加:

msgImage.add_header('Content-Disposition', 'inline', filename='filename')

所以,你最终得到:

from email.mime.multipart import MIMEMultipart

msgRoot = MIMEMultipart('related')
msgAlternative = MIMEMultipart('alternative')
...

# image file
msgText = MIMEText('<img src="cid:image" alt="Smiley" title="title">', 'html')
msgAlternative.attach(msgText)

# In-line Image
with open('/Users/john/Desktop/2015-04-21_13.35.38.png', 'rb') as fp:
    msgImage = MIMEImage(fp.read())
msgImage.add_header('Content-ID', '<image>')
msgImage.add_header('Content-Disposition', 'inline', filename='filename')
msgRoot.attach(msgImage)

...
server.sendmail(sender, recipients, msgRoot.as_string())

大功告成。

您可能更喜欢@PascalvKooten 提到的方式,像这样创建 MIMEImage 实例:

msgImage = MIMEImage(fp.read(), filename='filename')

这也很像魅力。