leoking87
leoking87

Reputation: 13

Python Email attachment loses end-of-newline "\n"

My python script (as the following) can send a ".txt" attachment, but unfortunately the received attachment lost the "\n", so all lines are together which ruined my column format. Can anyone please give me a help? Thanks a lot!

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)

Update: The original file (opened in remote Unix server with VIM) is like this:original file format

The received file format is like this: received

Upvotes: 0

Views: 1110

Answers (1)

leoking87
leoking87

Reputation: 13

Thanks to @gixxer's hint. It is the format problem of the txt file itself. The end-of-line character in the original txt is "\n" which works well on Unix system, but not on Windows. Windows uses "\r\n" instead. So I just add "\r\n" to the end of each line in the original file, and then it works.

Upvotes: 1

Related Questions