如何用python发html和plain text格式的邮件

本文介绍了一种使用Python发送带HTML格式的电子邮件的方法。通过smtplib和email库,可以轻松实现从设置邮件内容到发送的全过程。示例中包含了如何构造包含纯文本及HTML格式的邮件正文。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import smtplib
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart


smtp_sever = smtplib.SMTP('smtp_host')

msgRoot = MIMEMultipart('related')
msg['From'] = sender
msg['To'] = recepient
msg['Subject'] = 'Hello'

msgAlernative = MIMEMultipart('alernative')
msgRoot.attach(msgAlernative)

html="<html><body>Hello world</body></html>
msgHtml = MIMEText(html, 'html')   
msgAlernative.attach(msgHtml)

text = 'Hello world'
msgTxt = MIMEText(text)
msgAlernative.attach(msgTxt)

smtp_server.sendmail(sender, recepient, msgRoot.as_string())

 

 

 

 

Python中,我们可以使用smtplibemail库来邮件,如果需要包含图片,通常会将图片作为附件附在邮件里。以下是一个简单的例子: ```python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate from email import encoders # 定义件人、收件人SMTP服务器等信息 sender = 'your_email@example.com' receiver = 'recipient_email@example.com' password = 'your_password' smtp_server = 'smtp.example.com' # 创建MIME对象 msg = MIMEMultipart() msg['From'] = sender msg['To'] = COMMASPACE.join(receiver) msg['Date'] = formatdate(localtime=True) # 邮件正文 text = MIMEText('这是一封带有图片的邮件', 'plain') msg.attach(text) # 添加图片作为附件 with open('image.jpg', 'rb') as f: image = MIMEBase('image', 'jpeg') image.set_payload(f.read()) encoders.encode_base64(image) image.add_header('Content-Disposition', 'attachment', filename='image.jpg') msg.attach(image) # 连接SMTP服务器并邮件 try: server = smtplib.SMTP(smtp_server, 587) server.starttls() # 开启TLS加密 server.login(sender, password) server.sendmail(sender, receiver, msg.as_string()) print("邮件送成功") except Exception as e: print("邮件送失败: ", str(e)) # 关闭连接 server.quit() ``` 在这个示例中,你需要替换`sender`, `receiver`, `password`, `smtp_server`为你实际的邮箱密码信息,以及图片文件路径。邮件正文部分可以自定义,图片文件应放在程序运行目录下。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值