在Python中,我试图通过SMTPlib发送消息。但是,该消息始终在from标头中发送整个消息,我不知道如何解决它。它之前没有这样做,但现在它总是这样做。这是我的代码:
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()
它有什么问题,有没有办法解决它?
答案 0 :(得分:0)
这一行是问题所在:
server.sendmail(msg['From'], [email], body)
您可以使用以下方法修复它:
server.sendmail(msg['From'], [email], msg.as_string())
您发送了body
而不是整条消息; SMTP
协议期望消息以标头开头......因此您会看到标题应该位于body
。
您还需要删除换行符。每rfc2822行换行字符不受欢迎:
消息由标题字段组成(统称为“标题” 消息“)跟随,可选地,由一个正文。标题是一个 具有特殊语法的字符行序列 这个标准。身体只是一系列人物 跟随标题并通过空行与标题分开 (即在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()