[英]Python Email attachment loses end-of-newline “\n”
我的python腳本(如下所示)可以發送“ .txt”附件,但不幸的是,收到的附件丟失了“ \\ n”,因此所有行都在一起,這破壞了我的列格式。 誰能幫我一個忙嗎? 非常感謝!
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = 'Subject of Email4'
mailbody = "This is the content of Email4"
msg.attach(MIMEText(mailbody))
with open("regresult.txt", "r") as fil:
part = MIMEApplication(
fil.read(),
Name=basename("regresult.txt")
)
part['Content-Disposition'] = 'attachment; filename="%s"' % basename('regresult.txt')
msg.attach(part)
更新:原始文件(在帶有VIM的遠程Unix服務器中打開)是這樣的: 原始文件格式
接收到的文件格式是這樣的: 收到
感謝@gixxer的提示。 這是txt文件本身的格式問題。 原始txt中的行尾字符為“ \\ n”,在Unix系統上效果很好,但在Windows上效果不佳。 Windows使用“ \\ r \\ n”代替。 因此,我只需在原始文件的每行末尾添加“ \\ r \\ n”,然后它就可以工作了。
import smtplib
import io
sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']
file = io.open('newfile.txt', 'r')
message = file.readlines()
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print("Successfully sent email")
except Exception:
print("Error: unable to send email")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.