2016-07-25 162 views
0

我的python腳本(如下所示)可以發送一個「.txt」附件,但不幸的是收到的附件丟失了「\ n」,所以所有行都在一起這破壞了我的列格式。任何人都可以請給我一個幫助嗎?非常感謝!Python電子郵件附件丟失換行符「 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

+0

你能顯示生成的附件文本嗎?和原文? –

+0

我認爲問題出在文本文件本身。上面的代碼非常簡單。 'MIMEApplication'簡單地使用base64對文本文件進行編碼,並且查看電子郵件的電子郵件客戶端對其進行解碼,而沒有任何複雜性。我在Windows中打開文本文件時遇到了一些問題,並且我缺少新的換行符。在附加.txt文件 – gixxer

+0

@joelgoldstick之前嘗試使用'unix2dos'或'dos2unix',我只能上傳兩種格式的圖像。無法找到上傳.txt附件的地方。 – leoking87

回答

0
import smtplib 
import io 

sender = '[email protected]' 
receivers = ['[email protected]'] 
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") 
0

感謝@ gixxer的暗示。這是txt文件本身的格式問題。原始txt中的行尾字符是「\ n」,它在Unix系統上運行良好,但在Windows上不行。 Windows使用「\ r \ n」代替。所以我只是在原始文件的每一行的末尾添加「\ r \ n」,然後它就可以工作。