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

coo*_*l77 7 python email smtplib

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

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'])
Run Code Online (Sandbox Code Playgroud)

我希望"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]
Run Code Online (Sandbox Code Playgroud)

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

我怎么能根据我的需要解决这个问题.

Mat*_*ido 17

这应该工作:

msg['From'] = "Your name <Your email>"
Run Code Online (Sandbox Code Playgroud)

示例如下:

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')
Run Code Online (Sandbox Code Playgroud)

  • 效果很好!谢谢。但是,我注意到一些电子邮件客户端(例如较旧的 Outlook)会将收件箱中的 &lt;your@email.com&gt; 显示为发件人。我认为正确的方法是导入`from email.header import Header`和`from email.utils import formataddr`并执行:`msg['From'] = formataddr((str(Header('Your名称', 'utf-8')), 'your@email.com'))` (3认同)

Sre*_*Das 0

这应该可以修复它:

mail_me(cont,['xyz@xyzcom']) 用。。。来代替

mail_me(cont,'xyz@xyz.com')
Run Code Online (Sandbox Code Playgroud)