将图片嵌入Email的两种方法

2019年7月29日 / 2,731次阅读 / Last Modified 2019年8月19日
Email

Email内容部分最常见的就是图片了,我们一般有两种方法将图片嵌入Email。本文介绍这两种方法的Python实现。

发送HTML邮件

使用HTML格式的Email内容,只需要使用<img>元素,就可以引用一张外部图片。这个方法很简单,但是有一个小缺陷,很多Email服务提供商都会限制引用的外部图片,以免引起一些安全问题。所有,对于邮件接受者,可能要多点一下鼠标,选择信任此发件人等等,才能看到引用的外部图片,比如QQ信箱。

关于如何发送HTML邮件,请参考:如何用Python发送Email?

引用邮件内的图片

这种方法,其实也是发送HTML内容的Email,不同的是,<img>元素引用的不是外部图片,而是邮件内的图片资源。

回忆一下如何发送带附件的Email,我们可以将一个图片作为附件发送,其实我们也可以将一个图片作为内容来发送。先看代码:

import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

msg = MIMEMultipart('related')
msg_str = """
<p>send email with inside picture</p>
<img src="cid:123">
"""
msg.attach(MIMEText(msg_str, 'html', 'utf-8'))
pic = MIMEBase('image','jpg')
pic.add_header('Content-ID', '<123>')
with open('logo.jpg','rb') as f:
    pic.set_payload(f.read())
encoders.encode_base64(pic)
msg.attach(pic)

msg['From'] = 'from@qq.com'
msg['To'] = 'to@qq.com'
msg['Subject'] = Header('Email with inside picture','utf-8').encode()
smtp = smtplib.SMTP_SSL('smtp.qq.com')
smtp.login('from@qq.com','password')
smtp.sendmail('from@qq.com', 'to@qq.com', msg.as_string())
smtp.quit()

MIMEMultipart对象使用related;在创建MIMEBase对象之后,只有一个add_header,就是Content-ID,这个ID与msg_str里面的<img src="ID">对应。这就是引用邮件内的图片资源。然后发送即可,亲测成功:

引用邮件内图片资源的Email
引用邮件内图片资源的Email

我再补充一个小技巧,使用MIMEImage对象,上代码,关注高亮的行与上面那段代码的区别:

import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email import encoders

msg = MIMEMultipart('related')
msg_str = """
<p>send email with inside picture</p>
<img src="cid:123">
"""
msg.attach(MIMEText(msg_str, 'html', 'utf-8'))
with open('logo.jpg','rb') as f:
    pic = MIMEImage(f.read())
    pic.add_header('Content-ID','<123>')
    msg.attach(pic)

msg['From'] = 'from@qq.com'
msg['To'] = 'to@qq.com'
msg['Subject'] = Header('Email with inside picture','utf-8').encode()
smtp = smtplib.SMTP_SSL('smtp.qq.com')
smtp.login('from@qq.com','password')
smtp.sendmail('from@qq.com', 'to@qq.com', msg.as_string())
smtp.quit()

上面两段代码,效果是一样的!

以上就是用Python实现在Email内容中显示图片的两种方式的介绍。

-- EOF --

本文链接:https://www.pynote.net/archives/697

留言区

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


前一篇:
后一篇:

More

麦新杰的Python笔记

Ctrl+D 收藏本页


©Copyright 麦新杰 Since 2019 Python笔记

go to top