Python 使用smtplib.SMTP.sendmail发送HTML邮件时被截断的电子邮件

Python 使用smtplib.SMTP.sendmail发送HTML邮件时被截断的电子邮件,python,html,email,smtplib,Python,Html,Email,Smtplib,我遇到了一个奇怪的问题,我的电子邮件的最后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 th

我遇到了一个奇怪的问题,我的电子邮件的最后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 "\n\n"
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()
#获取运行时参数。
主题=args[0]
content=str(args[1])。replace(“\\n”,“
”)#Python会在运行时参数中自动转义反斜杠,因此“\n”会变为“\\n”。 #创建电子邮件。 msg=MIMEText(内容为“html”) msg['From']=发件人 msg['To']=“,”。加入(收件人) msg['Subject']=主语 打印“发送主题为\+主题为+”的电子邮件至:“+”,”。加入(收件人) 打印“内容:\n”+内容; 打印“\n\n” 打印“msg.as_字符串():\n”+msg.as_字符串() #设置SMPTP服务器,并发送电子邮件。 s=smtplib.SMTP(服务器) s、 sendmail(发送者、接收者、msg.as_string()) s、 退出
正如您在代码中所看到的,我将内容和最终消息打印到屏幕上,这两个都正确打印。但当收件人收到电子邮件时,它会被截断。我不能100%确定它是被一定数量的字符截断,还是在一定数量的字符之后截断,但我怀疑是后者

奇怪的是,如果电子邮件是以纯文本格式而不是HTML格式发送的,那么它们就可以正常发送。但不幸的是,大多数收件人使用Outlook,它认为它比我更清楚在纯文本电子邮件中的新行放在哪里

如有任何见解,将不胜感激

编辑:我还应该提到,这不是格式良好的HTML。基本上,我只是用

<br/>


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

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

如果您指定
内容传输编码:binary
,理论上您可以传递任意长度的行,但更好、更安全的做法是坚持
7bit
允许的内容传输编码,并使用合适的
内容传输编码,如
引用可打印的
或(如果您真的想疯狂)
base64

要详细说明您的答案,您可以这样做:

import quopri

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

谢谢现在我将“\\n”替换为“\n
”,它工作正常。我刚刚在连接长字符串时添加了\n“newline”运算符。它解决了电子邮件截短的问题。这是一个半措施,只有在HTML行长度不超过1000字节时才有效。同样,正确的解决方案是选择一种编码,该编码将原始邮件封装为对SMTP安全的格式,并在另一端解码回原始邮件。
import quopri

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