Python3 SMTP发送邮件
                           
天天向上
发布: 2025-03-16 12:43:58

原创
184 人浏览过

在 Python 中,使用 smtplib 库可以非常方便地实现通过 SMTP 服务器发送电子邮件。SMTP(Simple Mail Transfer Protocol)是用于电子邮件传输的标准协议。下面是一个使用 Python3 发送邮件的示例。

1. 基本的 SMTP 发送邮件

首先,你需要有一个邮件服务器的地址和登录凭据。以 Gmail 为例,下面的代码展示了如何使用 smtplib 发送一封简单的文本邮件。

示例代码:

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

# 邮件发送者、接收者和 SMTP 服务器信息
sender_email = "your_email@gmail.com"  # 替换为你的发件人邮箱
receiver_email = "recipient_email@example.com"  # 替换为收件人邮箱
password = "your_email_password"  # 替换为你的邮箱密码

# 设置邮件内容
subject = "Test Email from Python"
body = "This is a test email sent from Python using smtplib."

# 创建邮件消息
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))

# 连接到 Gmail SMTP 服务器
try:
    # 使用 SSL 连接 SMTP 服务器
    with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
        # 登录到邮件服务器
        server.login(sender_email, password)

        # 发送邮件
        server.sendmail(sender_email, receiver_email, message.as_string())
        print("Email sent successfully!")
except Exception as e:
    print(f"Error: {e}")

2. 代码解析:

  • MIMETextMIMEMultipart 是用来构建邮件的 MIME 类型格式。MIMEText 用于文本邮件,MIMEMultipart 用于多部分邮件(例如含附件的邮件)。
  • 你需要提供 SMTP 服务器的地址及端口号,这里是 Gmail 的 SMTP 服务器:smtp.gmail.com,端口号为 465(使用 SSL 安全连接)。
  • 使用 server.login() 来登录到你的邮箱,server.sendmail() 负责发送邮件。

3. 注意事项:

  1. Gmail 安全设置: 如果你使用 Gmail 发送邮件,需要开启 “低安全性应用的访问权限” 或使用应用专用密码。
  2. 密码安全: 避免直接在代码中暴露邮箱密码,最好通过环境变量或配置文件来管理密码。
  3. 其他邮件服务: 如果你使用的是其他邮件服务(如 Yahoo、Outlook 等),你需要更改 SMTP 服务器地址和端口。

4. 发送 HTML 格式的邮件

如果你想发送 HTML 格式的邮件,只需修改 MIMEText 的第二个参数为 "html"

html_body = """
<html>
  <body>
    <h1>This is a test email</h1>
    <p>Sent from <b>Python</b> via <i>SMTP</i>!</p>
  </body>
</html>
"""

message.attach(MIMEText(html_body, "html"))

5. 发送带附件的邮件

如果你需要发送带附件的邮件,可以使用 MIMEBase 来添加附件。

from email.mime.base import MIMEBase
from email import encoders

# 附件文件路径
attachment_path = "path_to_file"
filename = "example.txt"

# 打开文件并读取为附件
with open(attachment_path, "rb") as attachment_file:
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment_file.read())
    encoders.encode_base64(part)
    part.add_header("Content-Disposition", f"attachment; filename={filename}")

    message.attach(part)

以上是基本的 SMTP 邮件发送示例。更多详细内容请关注其他相关文章!

发表回复 0

Your email address will not be published. Required fields are marked *