Python电子邮件附件丢失了换行符“\ n”

时间:2016-07-25 17:13:42

标签: python email format attachment

我的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服务器中打开)如下所示:original file format

收到的文件格式如下:received

2 个答案:

答案 0 :(得分:1)

感谢@ gixxer的提示。这是txt文件本身的格式问题。原始txt中的行尾字符是" \ n"它适用于Unix系统,但不适用于Windows。 Windows使用" \ r \ n"代替。所以我只想添加" \ r \ n"到原始文件中每一行的末尾,然后它就可以了。

答案 1 :(得分:0)

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")