使用smtplib发送HTML消息时截断的电子邮件.SMTP发送邮件



我遇到了一个奇怪的问题,我的电子邮件的最后10-20个字符被截断了。

发送电子邮件的代码如下:

#Get the runtime arguments.
subject = args[0]
content = str(args[1]).replace("\n","<br/>") #Python automatically escapes the backslash in runtime arguments, so "n" turns into "\n".
#Create the email message.
msg = MIMEText(content, 'html')
msg['From']=sender
msg['To']=",".join(recipients)
msg['Subject']=subject
print "Sending email with subject ""+subject+"" to: " + ",".join(recipients)
print "Content: n" + content;
print "nn"
print "msg.as_string(): n" + msg.as_string()
#Set the SMPTP server, and send the email.
s = smtplib.SMTP(server)
s.sendmail(sender,recipients,msg.as_string())
s.quit()

正如您在代码中看到的,我将内容和最终消息都打印到屏幕上,这两个消息都打印正确。但当收件人收到电子邮件时,它会被截断。我不能100%确定它是被截断了一定数量的字符,还是在截断了一定量的字符之后,但我怀疑是后者。

奇怪的是,如果电子邮件以纯文本而不是HTML格式发送,则发送得很好。但不幸的是,大多数收件人都使用Outlook,Outlook认为它比我更清楚在纯文本电子邮件中添加新行。。。

任何见解都将不胜感激。

编辑:我还应该指出,这不是一个格式良好的HTML。基本上,我只是用替换新的线路

<br/>

我不确定这是否会有什么不同。除了brake标记之外,没有任何东西与HTML标记非常相似,所以问题不在于意外的标记扰乱了格式。

如果要从电子邮件中删除所有换行符,则会遇到麻烦。SMTP服务器通常不接受长度超过1000个字符的行。如果您想发送自由格式的数据,请将其封装在类似Quoted Printable的东西中(在那里您可以放置"不可见"的换行符,这些换行符将被客户端删除——不过,请注意正确地对消息本身进行QP编码)。

In quoted printable (RFC 2045), you can hex-encode any =22special=22 chara=
cter, like this (or=20in=20fact,=20any=20character=20at=all), and add line=
 breaks where you see fit by prefixing them with an equals sign.  Of cours=
e, you also have to encode any literal equals sign, like this: =3D.  Bette=
r use a library which understands the details of this format than write yo=
ur own encoder, though.

如果您指定了Content-Transfer-Encoding: binary,理论上您可以在任意长度的行中通过,但更好、更安全的做法是坚持7bit允许的内容,并使用合适的Content-Transfer-Encoding,如quoted-printable或(如果您想非常狂野)base64

要详细说明三元组的答案,以下是您在实践中的做法:

import quopri
#Create the email message.
content = quopri.encodestring(content)
msg = MIMEText(content, 'html')
msg.replace_header('content-transfer-encoding', 'quoted-printable')
...

最新更新