发送smtp邮件,当我收到邮件时,会显示纯文本版本和html版本。这样做的目的是从Sendgrid接收传入的电子邮件字典,然后将它们发送给另一个用户。代码中引用的“message”对象是Sendgrid发布到我的端点的字典。
这是我看到的:
test
Me
Signature
test
Me
Signature
这是我发送给邮件服务器的字符串:
Content-Type: multipart/mixed; boundary="===============5453410005537724489=="
MIME-Version: 1.0
To: me+test@domain.com
From: Me <me@domain.com>
Subject: test
reply-to: Original Sender <sender@theirdomain.com>
--===============5453410005537724489==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
test
Me
Signature
--===============5453410005537724489==
Content-Type: text/html; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
<html><head><meta http-equiv="Content-Type" content="text/html charset=us-ascii"></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;" class=""><span class="Apple-tab-span" style="white-space:pre"> </span>test<br class=""><div apple-content-edited="true" class="">
<span>Me</span><br><span>Signature</span>
</div>
<br class=""></body></html>
--===============5453410005537724489==--
最后,这是我用来发送电子邮件的Python代码:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
subject = message.get('subject', 'No Subject')
text = message.get('text', None)
html = message.get('html', None)
to = message.get('to')
cc = message.get('cc', None)
reply_to = message.get('from')
msg = MIMEMultipart()
msg['To'] = 'me+test@domcin.com'
msg['From'] = 'me@domain.com'
msg['Subject'] = subject
msg.add_header('reply-to', reply_to)
toaddrs = msg['To']
if cc is not None:
msg['CC'] = ', '.join(cc)
toaddrs += ', ' + msg['CC']
if text is not None:
msg.attach(MIMEText(text[0].encode('ascii', 'ignore'), 'plain'))
else:
msg.attach(MIMEText('No plain text for this email', 'plain'))
if html is not None:
msg.attach(MIMEText(html[0].encode('ascii', 'ignore'), 'html'))
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(GMAIL_USERNAME, GMAIL_PASSWORD)
mailServer.sendmail(GMAIL_USERNAME, toaddrs, msg.as_string())
mailServer.quit()
这里我缺了什么?