利用python编写程序,发送一个html格式的电 子邮件到账号为: 1694119803的qq邮箱 ,邮件内容包含https://www.7zwd.com/这个网页,再加上图片
时间: 2024-10-25 21:17:06 浏览: 20
要使用Python编写程序发送HTML格式的电子邮件,可以借助`smtplib`和`email`库。首先,你需要安装这两个库,如果没有安装,可以使用以下命令:
```bash
pip install smtplib email
```
接下来是一个示例代码,它会创建一封包含网页链接和图片的HTML邮件,并发送到指定的QQ邮箱:
```python
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" # 发送者的邮箱地址
password = "your_email_password" # 发送者邮箱的授权码
receiver_email = "1694119803@qq.com"
# 创建MIMEMultipart对象作为邮件容器
msg = MIMEMultipart("alternative")
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = "测试HTML邮件"
# 设置HTML邮件正文
body = f"""
<html>
<head></head>
<body>
<p>欢迎访问<a href="https://www.7zwd.com/">7zwd网站</a></p>
<img src="cid:image1" alt="图片">
</body>
</html>
"""
# 添加HTML文本
part1 = MIMEText(body, 'html')
msg.attach(part1)
# 添加图片
with open('image.jpg', 'rb') as f: # 指定本地图片文件名
image = MIMEImage(f.read())
image.add_header('Content-ID', '<image1>') # 标记图片id
msg.attach(image)
# SMTP服务器设置
smtp_server = "smtp.qq.com"
smtp_port = 587
smtp_ssl = True # QQ邮箱通常需要SSL连接
try:
with smtplib.SMTP(smtp_server, smtp_port) as server:
if smtp_ssl:
server.starttls()
server.login(sender_email, password)
text = msg.as_string()
server.sendmail(sender_email, receiver_email, text)
print("邮件已成功发送!")
except Exception as e:
print(f"发送邮件失败: {str(e)}")
阅读全文