如何在Python中使用MIMEText发送纯文本电子邮件
发布时间:2023-12-23 09:52:37
在Python中,可以使用smtplib和email库来发送电子邮件。下面是一个使用MIMEText发送纯文本电子邮件的例子:
import smtplib
from email.mime.text import MIMEText
# 邮件的发送方和接收方
sender = 'sender@example.com'
receiver = 'receiver@example.com'
# 构造邮件内容
message = MIMEText('这是一封纯文本邮件。', 'plain', 'utf-8')
message['Subject'] = '测试邮件'
message['From'] = sender
message['To'] = receiver
# 发送邮件
try:
smtpObj = smtplib.SMTP('smtp.example.com', 25)
smtpObj.login('username', 'password')
smtpObj.sendmail(sender, receiver, message.as_string())
smtpObj.quit()
print('邮件发送成功')
except smtplib.SMTPException as e:
print('邮件发送失败: ', str(e))
上述代码需要替换sender@example.com、receiver@example.com、smtp.example.com、username和password等信息为相应的邮箱地址和SMTP服务器地址、用户名和密码。
代码中首先导入了smtplib和email.mime.text模块,其中smtplib用于发送邮件,email.mime.text用于构造纯文本的邮件内容。然后,定义了发送方和接收方的邮箱地址。
接下来,使用MIMEText构造了一封纯文本的邮件, 个参数是邮件正文内容,第二个参数是邮件类型为plain表示纯文本,第三个参数是字符集为utf-8。然后,给邮件设置主题、发送方和接收方。
最后,通过smtplib.SMTP类连接到SMTP服务器,调用login方法登录邮箱,然后使用sendmail方法发送邮件,并通过quit方法断开连接。
如果邮件发送成功,则打印邮件发送成功,否则打印邮件发送失败以及错误信息。
以上即为使用MIMEText发送纯文本电子邮件的示例。
