Python发邮件常用方式汇总

在 Python 中发送邮件的常用方式主要依赖标准库 smtplib(处理 SMTP 协议)和 email(构造邮件内容),同时也存在一些第三方库和服务。以下是常见的实现方式及示例:


一、使用 smtplib + email 标准库

1. 发送纯文本邮件

python

import smtplib

from email.mime.text import MIMEText

from email.utils import formataddr


# 邮件配置

smtp_server = "smtp.example.com" # SMTP服务器地址(如QQ邮箱:smtp.qq.com)

port = 465 # 通常SSL端口为465,非加密为25或587

sender = "sender@example.com"

password = "your_password" # 邮箱密码或授权码(如QQ邮箱需用授权码)

receiver = "receiver@example.com"


# 构造邮件

msg = MIMEText("这是一封纯文本邮件。", "plain", "utf-8")

msg["From"] = formataddr(("发件人名称", sender))

msg["To"] = formataddr(("收件人名称", receiver))

msg["Subject"] = "邮件主题"


# 发送邮件

try:

with smtplib.SMTP_SSL(smtp_server, port) as server:

server.login(sender, password)

server.sendmail(sender, [receiver], msg.as_string())

print("邮件发送成功")

except Exception as e:

print(f"发送失败: {e}")

2. 发送HTML邮件

python

html_content = """

<html>

<body>

<h1>这是一封HTML邮件</h1>

<p><a href="https://example.com">点击链接</a></p>

</body>

</html>

"""

msg = MIMEText(html_content, "html", "utf-8")

# 其余配置同上

3. 发送带附件的邮件

python

from email.mime.multipart import MIMEMultipart

from email.mime.application import MIMEApplication


msg = MIMEMultipart()

msg.attach(MIMEText("正文内容", "plain", "utf-8"))


# 添加附件

with open("file.pdf", "rb") as f:

attach = MIMEApplication(f.read(), Name="file.pdf")

attach["Content-Disposition"] = 'attachment; filename="file.pdf"'

msg.attach(attach)


# 设置邮件头信息后发送


二、使用第三方库 yagmail(简化操作)

安装:pip install yagmail

python

import yagmail


# 配置账号(首次使用会提示输入密码)

yag = yagmail.SMTP(user="sender@example.com", password="your_password", host="smtp.example.com")


# 发送邮件(自动处理附件和HTML)

contents = [

"正文内容",

"可添加多个段落或HTML内容",

yagmail.inline("image.jpg"), # 内嵌图片

"file.pdf" # 附件路径

]


yag.send(

to="receiver@example.com",

subject="邮件主题",

contents=contents

)


三、使用企业邮箱服务(示例:腾讯企业邮)

python

smtp_server = "smtp.exmail.qq.com"

port = 465

sender = "name@company.com"

password = "企业邮箱密码"


# 使用 smtplib 的代码同上,配置对应服务器和认证信息即可


四、通过第三方API服务(如 SendGrid)

安装:pip install sendgrid

python

from sendgrid import SendGridAPIClient

from sendgrid.helpers.mail import Mail


api_key = "YOUR_SENDGRID_API_KEY"


message = Mail(

from_email="sender@example.com",

to_emails="receiver@example.com",

subject="邮件主题",

html_content="<strong>HTML内容</strong>"

)


try:

sg = SendGridAPIClient(api_key)

response = sg.send(message)

print(f"状态码: {response.status_code}")

except Exception as e:

print(f"错误信息: {e}")


五、其他服务(如 Mailgun)

安装:pip install requests

python

import requests


api_url = "https://api.mailgun.net/v3/YOUR_DOMAIN/messages"

api_key = "YOUR_MAILGUN_API_KEY"


response = requests.post(

api_url,

auth=("api", api_key),

data={

"from": "sender@example.com",

"to": ["receiver@example.com"],

"subject": "邮件主题",

"text": "纯文本内容",

"html": "<b>HTML内容</b>"

}

)


print(response.status_code)


注意事项

  1. 安全性

O 避免在代码中硬编码密码,推荐使用环境变量或配置文件。

O 使用加密连接(如 SMTP_SSL 或 starttls())。

  1. 常见问题

O Gmail 需开启 允许不够安全的应用(不推荐)或使用 OAuth2 认证。

O 国内邮箱(如 QQ、163)通常需要 授权码 而非明文密码。

  1. 反垃圾邮件

O 避免频繁发送相同内容,确保发件人信息合法。

根据需求选择合适的方式:标准库灵活但复杂,第三方库(如 yagmail)简化流程,API 服务适合大规模发送。