在python中电子邮件的发件人字段中添加发件人的姓名 [英] add sender's name in the from field of the email in python

查看:119
本文介绍了在python中电子邮件的发件人字段中添加发件人的姓名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to send email with below code.

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。但是当我收到电子邮件时,我在电子邮件的发件人字段中收到奇怪的详细信息。

I want "XYZ ABC" to appear as the sender's name when the email is received and its email address as 'sender@sender.com'. but when i receive email i am receiving weird details in "from" fields of the email message.

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

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

I have attached a screenshot of the email that i receive.

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

how can i fix this according to my need.

推荐答案

这应该有效:

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

这篇关于在python中电子邮件的发件人字段中添加发件人的姓名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆