在Python中使用MIMEText发送邮件并附加MIME图片内容
发布时间:2023-12-23 09:54:06
在Python中,使用MIMEText发送邮件并附加MIME图片内容,可以使用smtplib和email库来完成。
首先,我们需要导入相应的库:
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage
然后,我们需要设置邮件的发送者、接收者、主题等信息:
# 设置邮件信息 sender = "sender@example.com" recipient = "recipient@example.com" subject = "This is a test email"
接下来,我们需要创建一个MIMEMultipart的实例,用于包含邮件的文本内容和图片内容:
# 创建一个包含文本内容和图片内容的MIMEMultipart实例
msg = MIMEMultipart('related')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipient
然后,我们需要读取图片文件,并创建一个MIMEImage实例,将图片内容添加到MIMEMultipart实例中:
# 读取图片文件
image_data = open('image.jpg', 'rb').read()
# 创建一个MIMEImage实例
image = MIMEImage(image_data)
image.add_header('Content-ID', '<image1>')
image.add_header('Content-Disposition', 'inline', filename='image.jpg')
# 将图片添加到MIMEMultipart实例中
msg.attach(image)
接下来,我们需要设置邮件的正文内容,可以使用MIMEText实例来创建邮件的文本内容:
# 设置邮件的正文内容
text = MIMEText("""
<html>
<body>
<h1>This is a test email</h1>
<p>This email contains an inline image.</p>
<img src="cid:image1">
</body>
</html>
""", 'html')
# 将文本内容添加到MIMEMultipart实例中
msg.attach(text)
最后,我们需要使用smtplib库来发送邮件:
# 发送邮件
smtp_server = "smtp.example.com"
smtp_port = 587
smtp_username = "username"
smtp_password = "password"
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_username, smtp_password)
server.sendmail(sender, recipient, msg.as_string())
server.quit()
print("Email sent successfully")
except smtplib.SMTPException as e:
print("Error: unable to send email:", str(e))
以上就是使用MIMEText发送邮件并附加MIME图片内容的示例。代码中使用了MIMEMultipart、MIMEText和MIMEImage等类来创建邮件的内容,并使用smtplib库来发送邮件。在创建MIMEImage实例时,需要提供图片的字节数据,并设置Content-ID和Content-Disposition等头部信息,以便在邮件正文中引用图片。最后,通过调用MIMEMultipart实例的as_string()方法,将邮件内容转换为字符串形式发送。
