2017-09-26 92 views
0

我有多個文件預定義路徑的一部分,我試圖爲每個可用的txt文件生成一個電子郵件。 下面的代碼僅適用於一次,但每個文件每個電子郵件增加一個。在python中發送每個txt文件的附件電子郵件

您的輸入/建議將非常有幫助。 感謝, AL

#!/usr/bin/python 
import sys, os, shutil, time, fnmatch 
import distutils.dir_util 
import distutils.util 
import glob 
from os.path import join, getsize 
from email.mime.multipart import MIMEMultipart 
from email.mime.application import MIMEApplication 


# Import smtplib for the actual sending function 
import smtplib 
import base64 

# For guessing MIME type 
import mimetypes 

# Import the email modules we'll need 
import email 
import email.mime.application 


sourceFolder = "/root/email_python/" 
destinationFolder = r'/root/email_python/sent' 

# Create a text/plain message 
msg=email.mime.Multipart.MIMEMultipart() 
#msg['Subject'] = ' 
msg['From'] = '[email protected]' 
msg['To'] = '[email protected]' 

# The main body is just another attachment 
# body = email.mime.Text.MIMEText("""Email message body (if any) goes  here!""") 
# msg.attach(body) 


#To check if the directory is empty. 
#If directory is empty program exits and no email/file copy operations are carried out 
if os.listdir(sourceFolder) ==[]: 
    print "No attachment today" 
else: 

     for iFiles in glob.glob('*.txt'): 
     print (iFiles) 
    print "The current location of the file is " +(iFiles) 

    part = MIMEApplication(open(iFiles).read()) 
    part.add_header('Content-Disposition', 
      'attachment; filename="%s"' % os.path.basename(iFiles)) 
    shutil.move(iFiles, destinationFolder) 
    msg.attach(part) 
    #shutil.move(iFiles, destinationFolder) 
    #Mail trigger module 
    server = smtplib.SMTP('IP:25') 
    server.sendmail('[email protected]',['[email protected]'], msg.as_string()) 
    server.quit() 
    print "Email successfully sent!" 
    print "Files moved successfully" 

print "done" 
+0

你可以檢查你的代碼的縮進嗎? – strippenzieher

回答

1

這個問題就出現在這裏:

msg.attach(part) 

你在做什麼是附加部分此起彼伏,沒有清理以前附加部分。

您應該丟棄以前連接的零件,或重新初始化msg。在實踐中,重新初始化msg更容易。

# ... code before 

msg=email.mime.Multipart.MIMEMultipart() 
#msg['Subject'] = ' 
msg['From'] = '[email protected]' 
msg['To'] = '[email protected]' 

part = MIMEApplication(open(iFiles).read()) 
part.add_header('Content-Disposition', 
       'attachment; filename="%s"' % os.path.basename(iFiles)) 
shutil.move(iFiles, destinationFolder) 

# ... code after 
+0

非常感謝。包括它在循環中排序。 – user2335924

相關問題