Python中的邮件嵌入图片技巧
发布时间:2024-01-12 18:30:11
在Python中,我们可以使用email模块来发送包含嵌入图片的邮件。下面是一个简单的例子,演示如何使用Python发送嵌入图片的邮件。
首先,我们需要导入相应的模块:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage
然后,我们可以设置邮件的发送人、接收人、主题、正文等信息:
from_addr = 'sender@example.com' to_addr = 'recipient@example.com' subject = 'Embedded Image Example' body = 'This email contains an embedded image.'
接下来,我们需要读取图片文件,并将其转换为MIMEImage对象:
image_path = 'example.jpg'
with open(image_path, 'rb') as f:
image_data = f.read()
image = MIMEImage(image_data)
然后,我们可以将图片添加到正文中。正文需要使用HTML格式,并使用<img>标签来引用图片:
html = f"""\
<html>
<body>
<p>{body}</p>
<img src="cid:image" alt="Embedded Image">
</body>
</html>
"""
注意,<img>标签的src属性是cid:image,其中cid表示Content-ID,这是一种用于标识邮件中嵌入的图片的方法。Content-ID的值需要和MIMEImage对象的Content-ID头部字段一致:
image.add_header('Content-ID', '<image>')
接下来,我们可以创建MIMEMultipart对象,并将正文和图片添加到其中:
msg = MIMEMultipart() msg['From'] = from_addr msg['To'] = to_addr msg['Subject'] = subject msg.attach(MIMEText(html, 'html')) msg.attach(image)
最后,我们可以使用SMTP协议发送邮件:
smtp_server = 'smtp.example.com'
username = 'your_username'
password = 'your_password'
with smtplib.SMTP(smtp_server) as server:
server.login(username, password)
server.send_message(msg)
在上述代码中,需要将smtp.example.com替换为你的SMTP服务器地址,将your_username和your_password替换为你的SMTP用户名和密码。
完整的例子代码如下:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from_addr = 'sender@example.com'
to_addr = 'recipient@example.com'
subject = 'Embedded Image Example'
body = 'This email contains an embedded image.'
image_path = 'example.jpg'
with open(image_path, 'rb') as f:
image_data = f.read()
image = MIMEImage(image_data)
image.add_header('Content-ID', '<image>')
html = f"""\
<html>
<body>
<p>{body}</p>
<img src="cid:image" alt="Embedded Image">
</body>
</html>
"""
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = subject
msg.attach(MIMEText(html, 'html'))
msg.attach(image)
smtp_server = 'smtp.example.com'
username = 'your_username'
password = 'your_password'
with smtplib.SMTP(smtp_server) as server:
server.login(username, password)
server.send_message(msg)
以上代码将发送一封包含嵌入图片的邮件。邮件正文中将显示传入的文本,并且会显示一张名为example.jpg的图片。
需要注意的是,邮件中嵌入的图片可能在一些邮件客户端或网页邮箱中无法显示。因此, 在邮件中提供一个外链图片的备用链接,以便接收者可以在需要时手动查看图片。
希望这个例子能帮助你在Python中学习如何嵌入图片发送邮件。
