在Python email/smtplib中设置不同的回复地址

51 投票
5 回答
40217 浏览
提问于 2025-04-16 17:17

我正在用Python的email和smtplib库发送邮件,使用的是Gmail的SMTP服务器和我的Gmail账号。这一切都很顺利,不过我想设置一个不同于发件人地址的Reply-to邮件地址,这样回复邮件就会发送到一个其他的地址(不是Gmail的)。

我试着创建一个reply to参数,像这样:

   msg = MIMEMultipart()

   msg['From'] = "email@gmail.com"
   msg['To'] = to
   msg['Subject'] = subject
   msg['Reply-to'] = "email2@example.com"

但是这样不行。在Python的文档里找不到相关的信息。

5 个回答

5

对于2021年的Python3,我会推荐以下方法来构建消息:

from email.message import EmailMessage
from email.utils import formataddr

msg = EmailMessage()
msg['Subject'] = "Message Subject"
msg['From'] = formataddr(("Sender's Name", "email@gmail.com"))
msg['Reply-To'] = formataddr(("Name of Reply2", "email2@domain2.example"))
msg['To'] = formataddr(("John Smith", "john.smith@gmail.com"))
msg.set_content("""\
<html>
  <head></head>
  <body>
    <p>A simple test email</p>
  </body>
</html>
""", subtype='html')

然后,要发送消息,我使用以下代码,这个代码适用于我的邮件服务器,它在587端口上使用StartTLS:

from smtplib import SMTP
from ssl import create_default_context as context

with SMTP('smtp.domain.example', 587) as server:
    server.starttls(context=context())
    server.login('email@domain.example', password)
    server.send_message(msg)
25

我也遇到过同样的问题,解决的方法很简单,就是把请求头的字母都改成小写,像这样:

msg['reply-to'] = "email2@example.com"
56

这是我的看法。我认为“回复到”这个头部信息应该明确设置。原因可能是它的使用频率比“主题”、“收件人”和“发件人”等头部信息要少。

python
Python 2.6.6 (r266:84292, May 10 2011, 11:07:28)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> MAIL_SERVER = 'smtp.domain.example'
>>> TO_ADDRESS = 'you@gmail.com'
>>> FROM_ADDRESS = 'email@domain.example'
>>> REPLY_TO_ADDRESS = 'email2@domain2.example'
>>> import smtplib
>>> import email.mime.multipart
>>> msg = email.mime.multipart.MIMEMultipart()
>>> msg['to'] = TO_ADDRESS
>>> msg['from'] = FROM_ADDRESS
>>> msg['subject'] = 'testing reply-to header'
>>> msg.add_header('reply-to', REPLY_TO_ADDRESS)
>>> server = smtplib.SMTP(MAIL_SERVER)
>>> server.sendmail(msg['from'], [msg['to']], msg.as_string())
{}

撰写回答