Python邮件发送教程:使用email.mime.text模块发送纯文本电子邮件的方法
发布时间:2023-12-16 18:01:01
Python提供了email模块来发送电子邮件。在发送纯文本邮件时,可以使用email.mime.text模块。
以下是使用email.mime.text模块发送纯文本电子邮件的步骤:
1. 导入模块:
from email.mime.text import MIMEText
2. 创建MIMEText对象,设置邮件正文内容:
body = "This is the body of the email." msg = MIMEText(body)
3. 设置邮件的发送者和接收者:
msg['From'] = "sender@example.com" msg['To'] = "receiver@example.com"
4. 设置邮件的主题:
msg['Subject'] = "Subject of the email"
5. 发送邮件:
import smtplib
server = smtplib.SMTP('smtp.example.com', 587) # 这里使用了SMTP服务器,根据需要修改
server.starttls()
server.login("username", "password") # 根据实际情况替换为实际的用户名和密码
server.send_message(msg)
server.quit()
下面是一个完整的例子,演示如何使用email.mime.text模块发送一封纯文本邮件:
from email.mime.text import MIMEText
import smtplib
# 创建邮件内容
body = "This is the body of the email."
msg = MIMEText(body)
# 设置邮件发送者和接收者
msg['From'] = "sender@example.com"
msg['To'] = "receiver@example.com"
# 设置邮件主题
msg['Subject'] = "Subject of the email"
try:
# 发送邮件
server = smtplib.SMTP('smtp.example.com', 587) # 根据需要修改SMTP服务器地址和端口
server.starttls()
server.login("username", "password") # 根据实际情况替换为实际的用户名和密码
server.send_message(msg)
server.quit()
print("Email sent successfully!")
except Exception as e:
print("Error occurred while sending email:", str(e))
在实际发送邮件时,需要替换以下内容:
- "smtp.example.com":SMTP服务器的地址
- 587:SMTP服务器的端口号
- "sender@example.com":邮件发送者的邮箱地址
- "receiver@example.com":邮件接收者的邮箱地址
- "username":邮件发送者的用户名
- "password":邮件发送者的密码
确保在使用该代码发送邮件之前,已经开启了SMTP服务并正确设置了用户名和密码。
以上就是使用email.mime.text模块发送纯文本电子邮件的方法及使用示例。发送邮件时,请确保遵循相关的安全规定,并保护好用户名和密码等敏感信息。
