2017-09-26 6 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