【问题标题】:add sender's name in the from field of the email in python在 python 中的电子邮件的 from 字段中添加发件人的姓名
【发布时间】:2017-11-07 05:07:13
【问题描述】:

我正在尝试使用以下代码发送电子邮件。

import smtplib
from email.mime.text import MIMEText

sender = 'sender@sender.com'

def mail_me(cont, receiver):
    msg = MIMEText(cont, 'html')
    recipients = ",".join(receiver)
    msg['Subject'] = 'Test-email'
    msg['From'] = "XYZ ABC"
    msg['To'] = recipients
    # Send the message via our own SMTP server.
    try:
        s = smtplib.SMTP('localhost')
        s.sendmail(sender, receiver, msg.as_string())
        print "Successfully sent email"
    except SMTPException:
        print "Error: unable to send email"
    finally:
        s.quit()


cont = """\
   <html>
     <head></head>
     <body>
       <p>Hi!<br>
          How are you?<br>
          Here is the <a href="http://www.google.com">link</a> you wanted.
       </p>
     </body>
   </html>
   """
mail_me(cont,['xyz@xyzcom'])

我希望在收到电子邮件时显示“XYZ ABC”作为发件人的姓名,并将其电子邮件地址显示为“sender@sender.com”。但是当我收到电子邮件时,我会在电子邮件的“发件人”字段中收到奇怪的详细信息。

[![from:    XYZ@<machine-hostname-appearing-here>
reply-to:   XYZ@<machine-hostname-appearing-here>,
ABC@<machine-hostname-appearing-here>][1]][1]

我附上了我收到的电子邮件的屏幕截图。

如何根据我的需要解决这个问题。

【问题讨论】:

  • 你自己的smtp服务器配置成功了吗?

标签: python email smtplib


【解决方案1】:

这应该可行:

msg['From'] = "Your name <Your email>"

下面的例子:

import smtplib
from email.mime.text import MIMEText


def send_email(to=['example@example.com'],
               f_host='example.example.com',
               f_port=587,
               f_user='example@example.com',
               f_passwd='example-pass',
               subject='default subject',
               message='content message'):
    smtpserver = smtplib.SMTP(f_host, f_port)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(f_user, f_passwd)  # from email credential
    msg = MIMEText(message, 'html')
    msg['Subject'] = 'My custom Subject'
    msg['From'] = "Your name <Your email>"
    msg['To'] = ','.join(to)
    for t in to:
        smtpserver.sendmail(f_user, t, msg.as_string())  # you just need to add 
                                                         # this in for loop in 
                                                         # your code.
    smtpserver.close()
    print('Mail is sent successfully!!')

    cont = """
    <html>
    <head></head>
    <body>
    <p>Hi!<br>
      How are you?<br>
      Here is the <a href="http://www.google.com">link</a> you wanted.
    </p>
    </body>
    </html>
    """
    try:
        send_email(message=cont)
    except:
        print('Mail could not be sent')

【讨论】:

  • 欢迎来到 Stack Overflow!一般来说,最好提供一个带有解释的答案,也许是一个完整的例子。
  • 效果很好!谢谢。但是,我注意到一些电子邮件客户端(例如旧版 Outlook)会将收件箱中的 显示为发件人。我认为正确的方法是导入 from email.header import Headerfrom email.utils import formataddr 并执行:msg['From'] = formataddr((str(Header('Your name', 'utf-8')), 'your@email.com')).
  • 只想添加新案例。当我使用像 "Company Name CO., LTD &lt;email&gt;" 这样的文本时,它永远不会通过。但是当我写"(Company Name CO., LTD) &lt;email&gt;" 时它会起作用。 python 3.7
  • 这里不需要for循环。根据官方文档,sendmail 函数的第二个参数是 RFC 822 到地址字符串的列表(裸字符串将被视为具有 1 个地址的列表)。为了代码简单,我们可以只使用smtpserver.sendmail(f_user, to, msg.as_string())
  • 另外,如果您想遵循原始代码示例,应删除smtpserver.close() 行的缩进,以便能够发送到多个电子邮件地址。
【解决方案2】:
import smtplib
from email.mime.text import MIMEText

def send_email(to=['example@example.com'], f_host='example.example.com', f_port=587, f_user='example@example.com', f_passwd='example-pass', subject='default subject', message='content message'):
    smtpserver = smtplib.SMTP(f_host, f_port)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(f_user, f_passwd) # from email credential
    msg = MIMEText(message, 'html')
    msg['Subject'] = 'My custom Subject'
    msg['From'] = "Admin"
    msg['To'] = ','.join(to)
    for t in to:
        smtpserver.sendmail(f_user, t, msg.as_string())  # you just need to add this in for loop in your code.
        smtpserver.close()
    print('Mail is sent successfully!!')


cont = """\
   <html>
     <head></head>
     <body>
       <p>Hi!<br>
          How are you?<br>
          Here is the <a href="http://www.google.com">link</a> you wanted.
       </p>
     </body>
   </html>
   """
try:
    send_email(message=cont)
except:
    print('Mail could not be sent')

上述方法我尝试发送对我有用的邮件,即使我能够将邮件发送到我的 gmail 帐户(在垃圾邮件文件夹中)。 如果您遇到任何其他相关问题,请告诉我。

【讨论】:

    【解决方案3】:

    空格不是电子邮件地址中的有效字符。特殊字符只允许在应用双引号括起来的外部表示中。此外,大多数 SMTP 服务器实际上使用标头重写来确保地址采用标准格式。因为你的实际上包含一个空格,所以它被分割了,因为它没有用引号括起来,所以服务器地址被附加到它上面。

    您只需将msg['From'] = "XYZ ABC" 替换为

    msg['From'] = '"XYZ ABC"'
    

    强制将地址包含在双引号中。

    【讨论】:

      【解决方案4】:

      刚刚使用 gmx.com 测试了以下代码,它工作正常。虽然,您是否获得相同的里程是一个有争议的问题。
      我已将所有对我的电子邮件服务的引用替换为 gmail

      #!/usr/bin/python
      
      #from smtplib import SMTP # Standard connection
      from smtplib import SMTP_SSL as SMTP #SSL connection
      from email.MIMEMultipart import MIMEMultipart
      from email.MIMEText import MIMEText
      
      sender = 'example@gmail.com'
      receivers = ['example@gmail.com']
      
      
      msg = MIMEMultipart()
      msg['From'] = 'example@gmail.com'
      msg['To'] = 'example@gmail.com'
      msg['Subject'] = 'simple email via python test 1'
      message = 'This is the body of the email line 1\nLine 2\nEnd'
      msg.attach(MIMEText(message))
      
      ServerConnect = False
      try:
          smtp_server = SMTP('smtp.gmail.com','465')
          smtp_server.login('#name#@gmail.com', '#password#')
          ServerConnect = True
      except SMTPHeloError as e:
          print "Server did not reply"
      except SMTPAuthenticationError as e:
          print "Incorrect username/password combination"
      except SMTPException as e:
          print "Authentication failed"
      
      if ServerConnect == True:
          try:
              smtp_server.sendmail(sender, receivers, msg.as_string())
              print "Successfully sent email"
          except SMTPException as e:
              print "Error: unable to send email", e
          finally:
              smtp_server.close()
      

      【讨论】:

        【解决方案5】:

        名称来自FROM 标头。请参考这个答案Specify a sender when sending mail with Python (smtplib)

        【讨论】:

        • 是的。如果您看到代码,我在标题中使用了“发件人”。 msg['From'] = "XYZ ABC"
        【解决方案6】:

        这应该可以解决它:

        替换mail_me(cont,['xyz@xyzcom'])

        mail_me(cont,'xyz@xyz.com')
        

        【讨论】:

        • 不。这并不能解决问题。更多超过 smtplib 接受收件人的电子邮件地址作为列表。所以不能将其替换为字符串
        猜你喜欢
        • 2018-02-16
        • 1970-01-01
        • 1970-01-01
        • 2023-01-11
        • 2013-10-13
        • 2012-04-21
        • 1970-01-01
        • 2019-06-30
        • 1970-01-01
        相关资源
        最近更新 更多