You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法安装mailer模块求助及Python邮件发送替代方案咨询

无法安装mailer模块的解决方案及Python发送邮件替代方法

一、mailer模块安装失败的原因与可行尝试

你遇到的use_2to3 is invalid错误,是因为mailer-0.8.1是2012年发布的老旧版本,依赖Python2向Python3过渡的use_2to3工具,但新版pip(21.0+)已彻底移除对该参数的支持,导致元数据生成失败。

尝试以下方法解决安装问题:

  • 用旧版pip临时安装:执行pip install pip==20.3.4 && pip install mailer,但旧版pip存在安全风险,仅建议临时使用。
  • 安装第三方维护的Python3兼容版本:执行pip install mailer3(这是适配Python3的fork版本)。

如果以上方法仍无效,直接使用Python原生库实现邮件发送是更稳定的长期方案。

二、Python原生库发送邮件的脚本示例

Python内置的smtplib和email库可直接实现邮件发送,无需额外安装第三方包,以下是两种常见场景的示例:

1. 发送纯文本邮件

import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 邮箱配置
smtp_server = "smtp.qq.com"  # 替换为你的邮箱SMTP服务器,如smtp.gmail.com、smtp.163.com
smtp_port = 587  # 通常为587(TLS加密)或465(SSL加密)
sender = "your_email@qq.com"
password = "your_auth_code"  # QQ/163等邮箱需用授权码,而非登录密码
receiver = "target_email@example.com"

# 构造邮件内容
msg = MIMEText("这是测试邮件的正文内容", "plain", "utf-8")
msg["From"] = Header("发送者名称", "utf-8")
msg["To"] = Header("接收者名称", "utf-8")
msg["Subject"] = Header("纯文本测试邮件", "utf-8")

# 发送邮件
try:
    # 若使用465端口,替换为 smtplib.SMTP_SSL(smtp_server, 465)
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()  # 启用TLS加密
    server.login(sender, password)
    server.sendmail(sender, receiver, msg.as_string())
    print("邮件发送成功")
except Exception as e:
    print(f"发送失败: {str(e)}")
finally:
    server.quit()

2. 发送带附件的邮件

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from email.header import Header

# 邮箱配置
smtp_server = "smtp.qq.com"
smtp_port = 587
sender = "your_email@qq.com"
password = "your_auth_code"
receiver = "target_email@example.com"

# 创建带附件的邮件实例
msg = MIMEMultipart()
msg["From"] = Header("发送者名称", "utf-8")
msg["To"] = Header("接收者名称", "utf-8")
msg["Subject"] = Header("带附件的测试邮件", "utf-8")

# 添加正文
msg.attach(MIMEText("这是带附件的邮件正文", "plain", "utf-8"))

# 添加附件(替换为你的附件路径)
attachment_path = "test.pdf"
with open(attachment_path, "rb") as f:
    mime = MIMEBase("application", "octet-stream")
    mime.set_payload(f.read())
    encoders.encode_base64(mime)
    mime.add_header("Content-Disposition", f'attachment; filename="{attachment_path}"')
    msg.attach(mime)

# 发送邮件
try:
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(sender, password)
    server.sendmail(sender, receiver, msg.as_string())
    print("带附件的邮件发送成功")
except Exception as e:
    print(f"发送失败: {str(e)}")
finally:
    server.quit()

注意事项

  • 不同邮箱的SMTP服务器和端口不同,需自行查阅对应邮箱的帮助文档(如QQ邮箱需开启POP3/SMTP服务并生成授权码)。
  • 若使用SSL加密的465端口,需将smtplib.SMTP替换为smtplib.SMTP_SSL,且无需调用starttls()。

内容的提问来源于stack exchange,提问作者Luca The frog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:35:16