在python中发送每个txt文件的附件电子邮件
问题描述:
我有多个文件预定义路径的一部分,我试图为每个可用的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"
答
这个问题就出现在这里:
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
你可以检查你的代码的缩进吗? – strippenzieher