欢迎访问宙启技术站
智能推送

使用Python中的email.mime.image模块发送带图片的邮件实例

发布时间:2023-12-14 19:20:33

发送带图片的邮件可以使用Python中的email和smtplib模块来实现。其中,email.mime.image模块提供了创建邮件中图片附件的功能。下面给出一个使用email.mime.image模块发送带图片的邮件的例子。

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

# 邮件信息
mail_sender = "sender@example.com"
mail_receiver = "receiver@example.com"
mail_subject = "带图片的邮件"

# 创建邮件
msg = MIMEMultipart()
msg['From'] = mail_sender
msg['To'] = mail_receiver
msg['Subject'] = mail_subject

# 添加文本内容
text = "这是一封带图片的邮件"
text_part = MIMEText(text)
msg.attach(text_part)

# 添加图片附件
image_path = "example.jpg"
with open(image_path, 'rb') as f:
    image_data = f.read()
image_part = MIMEImage(image_data)
image_part.add_header('Content-Disposition', 'attachment', filename="example.jpg")
msg.attach(image_part)

# 发送邮件
try:
    server = smtplib.SMTP('smtp.example.com', 587)  # 邮件服务器和端口号
    server.starttls()
    server.login("your_username", "your_password")  # 登录邮箱
    server.send_message(msg)  # 发送邮件
    server.quit()
    print("邮件发送成功")
except Exception as e:
    print("邮件发送失败:", e)

以上代码中,首先定义了发送方、接收方和邮件主题。然后通过MIMEMultipart类创建了一个包含多个部分的邮件对象。使用MIMEText类添加了文本内容,使用MIMEImage类添加了图片附件。最后通过smtplib.SMTP类连接邮件服务器,登录邮箱,并发送邮件。

需要注意的是,邮件服务器地址和端口号需要根据实际情况进行修改。登录邮箱时,需要提供正确的用户名和密码。在打开图片文件时,需要提供正确的图片路径。使用具体的邮箱和密码时,需要将"your_username"和"your_password"修改为实际的值。

使用这个例子可以很方便地发送邮件,并在邮件中添加图片附件。