欢迎访问宙启技术站
智能推送

学习使用Pythonsend_mail()函数发送HTML格式的邮件

发布时间:2024-01-10 10:25:53

使用Python发送HTML格式的邮件需要用到smtplib库和email库。smtplib库负责实现邮件的发送功能,email库负责创建邮件对象和邮件内容的构造。

首先,需要导入smtplib和email库:

import smtplib
from email.mime.text import MIMEText

然后,需要创建一个MIMEText对象,用于表示邮件内容。MIMEText的参数有三个:邮件正文内容、文本类型(默认为plain,表示纯文本)、字符编码(默认为us-ascii)。

msg = MIMEText('<h1>Hello, World!</h1>', 'html', 'utf-8')

接下来设置邮件主题、发件人和收件人:

msg['Subject'] = 'Python邮件测试'
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'

然后,需要通过smtplib库创建一个SMTP对象,并登录到邮箱服务器:

smtp = smtplib.SMTP()
smtp.connect('smtp.example.com', 25)
smtp.login('sender@example.com', 'password')

登录成功后,通过SMTP对象的sendmail()方法发送邮件,该方法的参数有三个:发件人、收件人列表、邮件内容。

smtp.sendmail('sender@example.com', ['receiver1@example.com', 'receiver2@example.com'], msg.as_string())

最后,需要通过SMTP对象的quit()方法退出登录,并关闭与邮件服务器的连接。

smtp.quit()

下面是完整的使用例子:

import smtplib
from email.mime.text import MIMEText

msg = MIMEText('<h1>Hello, World!</h1>', 'html', 'utf-8')
msg['Subject'] = 'Python邮件测试'
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'

smtp = smtplib.SMTP()
smtp.connect('smtp.example.com', 25)
smtp.login('sender@example.com', 'password')
smtp.sendmail('sender@example.com', ['receiver1@example.com', 'receiver2@example.com'], msg.as_string())
smtp.quit()

通过以上代码,就可以使用Python发送HTML格式的邮件了。需要注意的是,在发送HTML格式的邮件时,需要将MIMEText的第二个参数设置为'html',并且确保邮件内容是合法的HTML代码格式。