在 Python 中电子邮件的发件人字段中添加发件人姓名



我试图发送带有以下代码的电子邮件。

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]

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

我该如何根据需要解决此问题。

这应该有效:

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')

刚刚使用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 1nLine 2nEnd'
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()

这应该修复:

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

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

名称来自FROM标头。请参阅此答案,请在使用Python(SMTPLIB(发送邮件时指定发件人

空间不是电子邮件地址中的有效字符。仅在外部表示中允许特殊字符以双引号包裹。另外,大多数SMTP服务器实际上使用标头重写来确保地址为标准格式。由于您的实际上包含了一个空间,并且由于没有用引号包装,因此服务器地址已附加到它。

您只需要用

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

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

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帐户(在垃圾邮件文件夹中(。让我知道您是否遇到其他相关问题。

虽然上述方法很好,但一种更明确的方法是从email.headerregistry

使用Address

地址类采用4个参数:(引用文档(

display_name-地址的显示名称部分(如果有(,所有引用删除。如果地址没有显示名称,则此属性将是一个空字符串。

username-地址的用户名部分,所有引用删除。

domain-地址的域部分。

addr_spec-地址的用户名@域部分,正确引用作为裸露地址的用作(上面显示的第二种形式(。此属性无法变形。

import smtplib
from email.message import EmailMessage
from email.headerregistry import Address
msg = EmailMessage()
msg.set_content('Hello Stackoverflow!')
msg['Subject'] = 'SO'
msg['From'] = Address(display_name="Name", addr_spec="info@mydomain.com")
msg['To'] = "receiver@domain.com"
# Send the message via our own SMTP server.
server = smtplib.SMTP_SSL('smpt.gmail.net', 465) # place your own host
server.login("info@mydomain.com", "mypassword")
server.send_message(msg)
server.quit()

最新更新