📜  Python使用SMTP发送电子邮件(1)

📅  最后修改于: 2023-12-03 14:46:42.541000             🧑  作者: Mango

Python使用SMTP发送电子邮件

在Python中,我们可以使用smtplib和email模块来发送电子邮件。smtplib模块负责连接SMTP服务器并发送邮件,而email模块负责构造邮件内容。

连接SMTP服务器

我们需要先连接SMTP服务器。SMTP服务器的地址、端口、用户名和密码都需要提供。

import smtplib

# SMTP服务器地址
SMTP_SERVER = 'smtp.example.com'

# SMTP服务器端口
SMTP_PORT = 587

# SMTP服务器用户名
SMTP_USERNAME = 'username'

# SMTP服务器密码
SMTP_PASSWORD = 'password'

# 创建SMTP客户端对象
smtp_client = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
smtp_client.ehlo()

# 启动TLS加密
smtp_client.starttls()
smtp_client.ehlo()

# 登录SMTP服务器
smtp_client.login(SMTP_USERNAME, SMTP_PASSWORD)
构造邮件内容

使用email模块构造邮件内容时,需要分别设置邮件的主题、发件人、收件人、邮件内容等。

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

# 邮件主题
subject = '测试邮件'

# 发件人
from_addr = 'from@example.com'

# 收件人
to_addr = 'to@example.com'

# 邮件内容,可以是纯文本或HTML格式
message = MIMEMultipart()
message.attach(MIMEText('这是一封测试邮件。'))

# 附件,可以传输任意二进制文件
attachment = MIMEApplication(b'Hello, World!', Name='hello.txt')
attachment['Content-Disposition'] = 'attachment; filename="hello.txt"'
message.attach(attachment)
发送电子邮件

设置好邮件内容后,我们即可调用SMTP客户端对象的sendmail方法来发送邮件。sendmail方法需要提供发件人、收件人和邮件内容三个参数。

# 发送邮件
smtp_client.sendmail(from_addr, to_addr, message.as_string())

# 退出SMTP服务器
smtp_client.quit()

以上就是使用Python发送电子邮件的基本流程。为了确保邮件能够被正常发送,服务器地址、端口、用户名和密码等参数必须正确。另外,邮件内容的构造也需要注意,必须按照RFC822标准进行编码。