Python SMTPlib:从 header 发送的邮件

Python SMTPlib: Message sending in from header

在 Python 中,我正在尝试通过 SMTPlib 发送消息。但是,该消息总是在 header 中发送整个消息,我不知道如何解决它。它以前不这样做,但现在它总是这样做。这是我的代码:

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

def verify(email, verify_url):
    msg = MIMEMultipart()
    msg['From'] = 'pyhubverify@gmail.com\n'
    msg['To'] = email + '\n'
    msg['Subject'] = 'PyHub verification' + '\n'
    body = """ Someone sent a PyHub verification email to this address! Here is the link: 
    www.xxxx.co/verify/{1}
    Not you? Ignore this email.
    """.format(email, verify_url)
    msg.attach(MIMEText(body, 'plain'))
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login('pyhubverify@gmail.com', 'xxxxxx')
    print msg.as_string()
    server.sendmail(msg['From'], [email], body)
    server.close()

有什么问题吗,有什么办法可以解决吗?

这一行是问题所在:

server.sendmail(msg['From'], [email], body)

您可以通过以下方式修复它:

server.sendmail(msg['From'], [email], msg.as_string())

您发送的是 body 而不是整个消息; SMTP 协议期望消息以 headers...

您还需要删除换行符。根据 rfc2822 line-feed 个字符单独不受欢迎:

A message consists of header fields (collectively called "the header of the message") followed, optionally, by a body. The header is a sequence of lines of characters with special syntax as defined in this standard. The body is simply a sequence of characters that follows the header and is separated from the header by an empty line (i.e., a line with nothing preceding the CRLF).

请尝试以下操作:

msg = MIMEMultipart()
email = 'recipient@example.com'
verify_url = 'http://verify.example.com'
msg['From'] = 'pyhubverify@gmail.com'
msg['To'] = email
msg['Subject'] = 'PyHub verification'
body = """ Someone sent a PyHub verification email to this address! Here is the link:
www.xxxx.co/verify/{1}
Not you? Ignore this email.
""".format(email, verify_url)
msg.attach(MIMEText(body, 'plain'))
print msg.as_string()