在python中为每个txt文件发送附件电子邮件

时间:2017-09-26 13:47:20

标签: python loops email attachment

我有多个文件是预定义路径的一部分,我正在尝试为每个可用的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'] = 'john@domain.com'
msg['To'] = 'user1@domain.com'

# 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('john@domain.com',['user1@domain.com'], msg.as_string())
  server.quit()
  print "Email successfully sent!"
  print "Files moved successfully"

print "done"

1 个答案:

答案 0 :(得分:1)

这个问题出现在这里:

msg.attach(part)

您在做什么是一个接一个地连接部件,而不清洁以前连接的部件。

您应丢弃以前连接的部件,或重新初始化msg。在实践中,重新初始化msg更容易。

# ... code before

msg=email.mime.Multipart.MIMEMultipart()
#msg['Subject'] = '
msg['From'] = 'john@domain.com'
msg['To'] = 'user1@domain.com'

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

# ... code after