跳到主要内容

如何用Python来发送邮件?

参考答案:

在Python中,你可以使用内置的smtplib模块以及email模块来发送邮件。下面是一个基本的示例,展示了如何使用这些模块发送一封简单的邮件:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# 设置邮件服务器的相关信息
smtp_server = 'smtp.example.com'  # 替换为你的SMTP服务器地址
port = 587  # 替换为你的SMTP服务器端口
sender_email = 'your-email@example.com'  # 替换为你的发件邮箱地址
sender_password = 'your-password'  # 替换为你的发件邮箱密码

# 创建SMTP服务器的连接
server = smtplib.SMTP(smtp_server, port)
server.starttls()  # 加密方式
server.login(sender_email, sender_password)

# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = 'recipient-email@example.com'  # 替换为收件人的邮箱地址
msg['Subject'] = 'Test Email'  # 邮件的主题

# 添加邮件正文
body = 'This is a test email sent from Python.'
msg.attach(MIMEText(body, 'plain'))

# 发送邮件
server.sendmail(sender_email, 'recipient-email@example.com', msg.as_string())

# 关闭SMTP服务器的连接
server.quit()

print('Email sent successfully!')

请注意,你需要将示例代码中的以下部分替换为你自己的信息:

  • smtp_server:你的SMTP服务器地址。
  • port:你的SMTP服务器端口。
  • sender_email:你的发件邮箱地址。
  • sender_password:你的发件邮箱密码。
  • msg['To']:收件人的邮箱地址。

此外,根据你的邮件服务提供商,你可能需要使用不同的SMTP服务器地址和端口,以及可能需要使用不同的加密方式(例如SSL而不是TLS)。因此,请确保根据你的具体情况进行调整。

另外,如果你使用的是Gmail等邮件服务提供商,你可能需要在你的账户设置中允许"不够安全的应用"的访问,或者使用OAuth2进行身份验证。这些步骤可能会因邮件服务提供商而异,因此请参考相关文档以获取更多详细信息。