如何使用Python编程语言发送一封包含文本内容、图片和附加文件(如PDF或文档)的HTML格式电子邮件?
时间: 2024-10-24 12:15:32 浏览: 17
python把文本转换为html-Python基础教程-把文本转为HTML格式.pdf
在Python中,我们可以使用内置的`smtplib`库来处理SMTP(简单邮件传输协议),以及`email`模块来构建邮件内容。以下是一个基本的例子,展示了如何发送一封包含文本、图片和附件的HTML格式电子邮件:
```python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
# 邮件信息
sender_email = "your_email@example.com"
receiver_email = "recipient_email@example.com"
password = "your_password" # 这里应为你的SMTP服务器密码
smtp_server = "smtp.example.com" # 这里应为你SMTP服务器地址
# 创建邮件对象
msg = MIMEMultipart('related') # multipart/related 标签用于包含HTML和图片
# 添加HTML文本
html_content = """
<html>
<head></head>
<body>
<p>Hello, this is an <img src="cid:image1"> message!</p>
</body>
</html>
"""
msg.attach(MIMEText(html_content, 'html'))
# 添加图片
with open("image1.jpg", "rb") as image_file:
img_part = MIMEImage(image_file.read())
img_part.add_header('Content-ID', '<image1>')
msg.attach(img_part)
# 添加附件
pdf_path = "document.pdf" # 替换为你的PDF文件路径
with open(pdf_path, "rb") as pdf_file:
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(pdf_file.read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', f'attachment; filename="{pdf_path}"')
msg.attach(attachment)
# 发送邮件
try:
server = smtplib.SMTP(smtp_server, 587) # 使用SMTP端口
server.starttls() # 加密连接
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg.as_string()) # 发送邮件
print("Email sent successfully.")
except Exception as e:
print(f"Error sending email: {str(e)}")
finally:
server.quit()
```
请注意,你需要替换上述代码中的`your_email@example.com`, `recipient_email@example.com`, `your_password`, 和 `smtp.example.com`为实际的邮箱地址、SMTP服务器信息和密码。
阅读全文