Python中使用smtplib库发送HTML格式的邮件的实现方式
发布时间:2023-12-25 13:26:07
Python中使用smtplib库发送HTML格式的邮件可以通过以下步骤实现:
1. 引入smtplib库和email库:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText
2. 创建一个MIMEMultipart对象,用于组合邮件的各个部分:
msg = MIMEMultipart()
3. 设置邮件的主题、发件人、收件人等信息:
msg['Subject'] = 'HTML email' msg['From'] = 'sender@example.com' msg['To'] = 'receiver@example.com'
4. 创建一个MIMEText对象,用于设置邮件正文:
html = """
<html>
<body>
<p>This is an HTML email.</p>
<p>Here is a link: <a href="https://www.example.com">Example</a>.</p>
</body>
</html>
"""
body = MIMEText(html, 'html')
msg.attach(body)
5. 连接邮件服务器并发送邮件:
mail_server = smtplib.SMTP('smtp.example.com', 587) # 邮件服务器地址和端口号
mail_server.starttls() # 开启TLS加密
mail_server.login('username', 'password') # 发件人邮箱用户名和密码
mail_server.send_message(msg) # 发送邮件
mail_server.quit() # 关闭连接
下面是一个完整的使用smtplib库发送HTML格式邮件的例子:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg['Subject'] = 'HTML email'
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'
html = """
<html>
<body>
<p>This is an HTML email.</p>
<p>Here is a link: <a href="https://www.example.com">Example</a>.</p>
</body>
</html>
"""
body = MIMEText(html, 'html')
msg.attach(body)
mail_server = smtplib.SMTP('smtp.example.com', 587)
mail_server.starttls()
mail_server.login('username', 'password')
mail_server.send_message(msg)
mail_server.quit()
使用上述代码,可以通过替换相应的发件人、收件人、邮件内容等信息,发送HTML格式的邮件。
