在 python 中的电子邮件的发件人字段中添加发件人姓名
我正在尝试使用以下代码发送电子邮件。
import smtplibfrom 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]
我附上了我收到的电子邮件的屏幕截图。
我该如何根据我的需要解决这个问题。
原文由 cool77 发布,翻译遵循 CC BY-SA 4.0 许可协议
回答:
这应该有效:
msg['From'] = "Your name <Your email>"
示例如下:
import smtplibfrom 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')
原文由 Matheus Candido 发布,翻译遵循 CC BY-SA 4.0 许可协议
回答:
楼上回答也可,在跨邮箱的情况下可能会出现乱码,最好从email.utils库里导入formataddr,利用其进行格式化会保险一些,formataddr(('your name', 'your email')),当然收件人,抄送也可以这样格式化输入,格式化结果为 =?utf-8?b?中文的utf-8编码?= <邮箱地址>
from email.utils import formataddrmessage['From'] = formataddr(('your name', 'your email'))
以上是 在 python 中的电子邮件的发件人字段中添加发件人姓名 的全部内容, 来源链接: utcz.com/p/938821.html