在Python中使用email.mime.multipart发送带图片的邮件
发布时间:2023-12-14 11:51:51
在Python中使用email.mime.multipart模块可以发送带有图片附件的邮件。下面是一个完整的例子:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
# 配置发送人邮箱信息
sender_email = "your_email@example.com"
sender_password = "your_password"
# 配置收件人邮箱信息
receiver_email = "recipient_email@example.com"
# 创建一个包含文本和图片的邮件
msg = MIMEMultipart()
# 设置邮件内容
msg.attach(MIMEText("Hello, this is a test email with an image attachment.", "plain"))
# 读取图片并添加到邮件中
with open("path_to_image.jpg", "rb") as image_file:
image = MIMEImage(image_file.read())
image.add_header('Content-Disposition', 'attachment', filename="image.jpg")
msg.attach(image)
# 设置邮件主题、发送人和收件人
msg['Subject'] = "Test email with image attachment"
msg['From'] = sender_email
msg['To'] = receiver_email
# 发送邮件
try:
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login(sender_email, sender_password)
server.send_message(msg)
server.quit()
print("Email sent successfully!")
except Exception as e:
print(f"Error sending email: {e}")
在上面的例子中,首先需要配置发送人和收件人的邮箱信息。然后,创建一个包含文本和图片的MIMEMultipart实例。使用MIMEText模块添加纯文本内容,使用MIMEImage模块读取图片文件,将图片添加到邮件中,并设置文件名。然后,设置邮件主题、发送人和收件人的属性。最后,通过smtplib模块中的SMTP类实例化一个SMTP服务器,登录并发送邮件,最后退出服务器。
注意:在代码中需要将"your_email@example.com"、"your_password"、"recipient_email@example.com"和"path_to_image.jpg"分别替换为你自己的邮箱地址、密码、收件人的邮箱地址和图片文件的路径。
