为了对电子邮件进行格式化处理,可以使用Python内置的email和email.mime模块。下面是一个示例代码,展示了如何创建一个带有附件的HTML邮件:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
# 创建MIMEMultipart对象作为根容器
msg_root = MIMEMultipart('related')
msg_root['Subject'] = 'This is the subject of the email'
msg_root['From'] = 'sender@example.com'
msg_root['To'] = 'recipient@example.com'
# 创建MIMEText对象用于显示邮件正文内容,并添加到根容器
msg_text = MIMEText('<p>Here is the <b>HTML</b> message body.</p>', 'html')
msg_root.attach(msg_text)
# 读取图片文件并作为MIMEImage添加到根容器
with open('image.jpg', 'rb') as f:
msg_image = MIMEImage(f.read())
msg_root.attach(msg_image)
# 将根容器转换成字符串并发送邮件
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.starttls()
smtp.login('sender@example.com', 'password')
smtp.sendmail('sender@example.com', 'recipient@example.com', msg_root.as_string())
smtp.quit()
在示例代码中,MIMEMultipart对象被用作最外层容器,MIMEText对象用于包含文本消息,MIMEImage对象用于包含邮件中的图像。调用as_string()方法来将邮件转换成字符串,并使用SMTP协议发送邮件。可以根据需要调整邮件的格式和内容。