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

send attachment email for each txt file in python

我有多个文件是预定义路径的一部分,我正在尝试为每个可用的 txt 文件生成一封电子邮件。 下面的代码只工作一次,但是随着每个文件的每封电子邮件递增。

您的 input/suggestion 会很有帮助。 谢谢, 阿尔

#!/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"

这个问题出现在这里:

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