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

bgibtngc  于 2022-11-21  发布在  Python
关注(0)|答案(5)|浏览(154)

我正在使用Python email和smtplib从Python发送一封邮件。我是通过Gmail SMTP服务器使用我的Gmail凭据来发送邮件的。这很好用,但是我想指定一个不同于fromReply-to电子邮件地址,这样回复就会发到一个单独的地址(非Gmail)。
我尝试过创建一个reply to参数,如下所示:

msg = MIMEMultipart()

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

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

fdbelqdn

fdbelqdn1#

以下是我的看法。我认为“Reply-To”头应该显式设置。可能的原因是它比“Subject”、“To”和“From”等头更不常用。

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())
{}
rslzwgfq

rslzwgfq2#

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

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

sxpgvts33#

对于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)
1tu0hz3e

1tu0hz3e4#

正如Jonathon Reinhart所指出的,“To”必须是大写的:

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

um6iljoc5#

只有这个对我有用:

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

看这里:Reply to email using python 3.4 by厄本

相关问题