【问题标题】:Python SMTP Emails Showing Both Plain and HTML Versions显示纯文本和 HTML 版本的 Python SMTP 电子邮件
【发布时间】:2023-04-01 18:33:01
【问题描述】:

发送一封 smtp 电子邮件,当我收到电子邮件时,它会背靠背显示纯文本版本和 html 版本。这样做的目的是从 Sendgrid 获取传入的电子邮件字典,然后将它们发送给另一个用户。代码中引用的“消息”对象是发送到我的端点的 dict 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()

我在这里错过了什么?

【问题讨论】:

    标签:
    python
    email
    smtp
    sendgrid