网页格式发送
for_email.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
h1 { color: brown; }
p { margin: 5px; color: purple; }
</style>
</head>
<body>
<h1>这是一个邮件内容的标头</h1>
<img src="https://img1.baidu.com/it/u=1890390320,3399874998&fm=253&fmt=auto&app=120&f=JPEG?w=1422&h=800">
<!-- 其他内容 -->
</body>
</html>
main.py
import smtplib
import time
from email.mime.text import MIMEText
def send_message():
"""
纯文本发送邮件
"""
sender = '[email protected]' # 发送邮箱地址
passwd = 'XXX456' # 授权码
receiver = '[email protected]' # 接收邮箱地址
# 创建纯文本内容
msg = MIMEText(f'Python 邮件发送测试 {time.time()}', 'plain', 'utf-8') # 第一个参数为邮件发送内容
msg['From'] = f'abc <{sender}>'
msg['To'] = receiver
msg['Subject'] = 'Python SMTP 邮件测试' # 邮件主题
try:
# 建立 SMTP、SSL 连接
smtp = smtplib.SMTP_SSL('smtp.qq.com', 465)
smtp.login(sender, passwd)
smtp.sendmail(sender, receiver, msg.as_string())
print('邮件发送成功')
smtp.quit()
except Exception as e:
print(e)
print('发送邮件失败')
def send_html_message():
"""
html格式发送
"""
sender = '[email protected]' # 发送邮箱地址
passwd = 'XXX456' # 授权码
receiver = '[email protected]' # 接收邮箱地址
# 读入 HTML 文件的内容
with open('./for_email.html', mode='r', encoding='utf-8') as f:
html_content = f.read()
# 指定类型为 HTML
msg = MIMEText(html_content, 'html', 'utf-8')
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = '测试发送 HTML 内容'
try:
smtp = smtplib.SMTP_SSL('smtp.qq.com', 465)
smtp.login(sender, passwd)
smtp.sendmail(sender, receiver, msg.as_string())
print('发送成功')
except:
print('发送失败')
if __name__ == '__main__':
send_message()
send_html_message()
标签:sender,python,SMTP,smtp,发送,html,msg,邮件
From: https://www.cnblogs.com/jackchen28/p/18332208