在Python中为每个TXT文件发送附件电子邮件



我有预定义路径的多个文件部分,我正在尝试为每个可用的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"

此问题在这里出现:

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

相关内容

  • 没有找到相关文章

最新更新