我有一段非常简单的代码(仅用于测试):
import smtplib
import time
server = 'smtp.myprovider.com'
recipients = ['[email protected]']
sender = '[email protected]'
message = 'Subject: [PGS]: Results\n\nBlaBlaBla'
session = smtplib.SMTP(server)
session.sendmail(sender,recipients,message);
这有效,但问题是电子邮件客户端不显示发件人。我希望能够在电子邮件中添加发件人姓名。建议?
smtplib
不会自动包含From:
标题,所以你必须自己加一个:
message = 'From: [email protected]\nSubject: [PGS]: Results\n\nBlaBlaBla'
(实际上,smtplib
不会自动包含任何标题,而只是将您提供的文本作为原始消息发送)
See这个答案,它对我有用。
示例代码:
#send html email
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
msg = MIMEMultipart('alternative')
msg['From'] = formataddr((str(Header('MyWebsite', 'utf-8')), '[email protected]'))
msg['To'] = '[email protected]'
html = "email contents"
# Record the MIME types of text/html.
msg.attach(MIMEText(html, 'html'))
# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail('[email protected]', '[email protected]', msg.as_string())
s.quit()
您可以使用email.message.Message类,并使用它来生成mime标头,包括from:
,to:
和subject
。通过SMTP发送as_string()
结果。
>>> from email import message
>>> m1=message.Message()
>>> m1.add_header('from','[email protected]')
>>> m1.add_header('to','[email protected]')
>>> m1.add_header('subject','test')
>>> m1.set_payload('test\n')
>>> m1.as_string()
'from: [email protected]\nto: [email protected]\nsubject: test\n\ntest\n'
>>>
在这种情况下,您指定的“发件人”是传递到SMTP服务器的信封发件人。
您的MUA(邮件用户代理 - 即outlook / Thunderbird等)显示的是“From:”标题。
通常,如果我使用smtplib,我会分别编译头文件:
headers = "From: %s\nTo: %s\n\n" % (email_from, email_to)
From标头的格式通常是"Name" <user@domain>
您应该在所有通信中包含“Message-Id”标头和“Reply-To”标头。特别是因为垃圾邮件过滤器可能会发现邮件是垃圾邮件的可能性很大。
如果你的邮件正文在变量体中,只需编译整个邮件:
message = headers + body
请注意标题末尾的双换行符。值得注意的是,SMTP服务器应该仅使用换行符分隔标题(即LF - linfeed)。但是,我见过一台或两台使用\ r \ n(即CRLF)的Windows SMTP服务器。如果您使用的是Windows,YMMV。
当只使用smtplib来添加名称而不是显示您的电子邮件地址时,只需使用:
message = """From: whatever-name\nSubject: subject\n\n
body of the message!
""".encode()
通过.sendmail(TO,FROM,message)传递此消息将起作用。