在Python email / smtplib中设置不同的回复消息

时间:2011-05-09 15:14:34

标签: python email smtplib

我正在使用Python电子邮件和smtplib从Python发送电子邮件。我是通过Gmail SMTP服务器使用我的Gmail凭据执行此操作的。这项工作正常,但我想指定一个与Reply-to地址不同的from电子邮件地址,以便回复转到单独的地址(非Gmail)。

我尝试过像这样创建reply to参数:

   msg = MIMEMultipart()

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

但这不起作用。在Python文档中找不到任何关于此的信息。

感谢。

5 个答案:

答案 0 :(得分:36)

这是我的看法。我认为应该明确设置“Reply-To”标题。可能的原因是它比标题更常用,例如“主题”,“收件人”和“发件人”。

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.com'
>>> TO_ADDRESS = 'you@gmail.com'
>>> FROM_ADDRESS = 'email@domain.com'
>>> REPLY_TO_ADDRESS = 'email2@domain2.com'
>>> 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())
{}

答案 1 :(得分:9)

我有同样的问题,而我所要做的就是将标题设置为小写,如下所示:

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

答案 2 :(得分:1)

对于 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.com"))
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.com', 587) as server:
    server.starttls(context=context())
    server.login('email@domain.com', password)
    server.send_message(msg)

答案 3 :(得分:0)

这仅对我有用:

msg['In-Reply-To'] = "email2@domain2.com"

在这里查看:[使用python 3.4回复电子邮件],由Urban 1

答案 4 :(得分:0)

正如乔纳森·莱因哈特(Jonathon Reinhart)所指出的那样,“收件人”必须为大写:

msg['Reply-To'] = "email2@domain2.com"