如何一次发送多封电子邮件,每封附有一个 xlsx 文件附件?
How to send multiple e-mails at once with one xlsx file attachment each?
我正在编写一个 Python 脚本,用于在目录中搜索具有特定名称的 .XLSX 文件,然后发送附有这些文件的电子邮件。
如果该目录中有 3 个 XLSX 文件,我想发送 3 封电子邮件,每封电子邮件都附有一个文件。我的代码发生了什么,在那个例子中,它发送了 3 封电子邮件:
- 第一封附有 1 个文件的电子邮件
- 第二个附有 2 个文件
- 第三个附有3个文件
我尝试将文件作为电子邮件的附件移动到另一个目录,但没有成功。这是代码:
for xlsxfile in glob.glob(os.path.join('.', 'START_OF_FILENAME_*.XLSX')):
xlsxpart = MIMEApplication(open(xlsxfile, 'rb').read())
xlsxpart.add_header('Content-Disposition', 'attachment', filename=xlsxfile[1:])
msg.attach(xlsxpart)
shutil.move(xlsxfile, './sent/'+xlsxfile[2:])
try:
client = smtplib.SMTP()
client.connect('XX.XXX.XX.XX', port=25)
client.sendmail(username, rcptlist, msg.as_string())
client.quit()
#...exception handling
for xlsxfile in glob.glob(os.path.join('.', 'START_OF_FILENAME_*.XLSX')):
...
msg.attach(xlsxpart)
...
在每次迭代中,当前文件都被添加到现有的 msg
对象中。当循环进行到第三次迭代时,msg
已经附加了前 2 个文件。
相反,每次迭代都应创建一个新的 msg
对象:
for xlsxfile in glob.glob(os.path.join('.', 'START_OF_FILENAME_*.XLSX')):
...
msg = Message(...) # however you created msg before the loop
msg.attach(xlsxpart)
...
我正在编写一个 Python 脚本,用于在目录中搜索具有特定名称的 .XLSX 文件,然后发送附有这些文件的电子邮件。 如果该目录中有 3 个 XLSX 文件,我想发送 3 封电子邮件,每封电子邮件都附有一个文件。我的代码发生了什么,在那个例子中,它发送了 3 封电子邮件:
- 第一封附有 1 个文件的电子邮件
- 第二个附有 2 个文件
- 第三个附有3个文件
我尝试将文件作为电子邮件的附件移动到另一个目录,但没有成功。这是代码:
for xlsxfile in glob.glob(os.path.join('.', 'START_OF_FILENAME_*.XLSX')):
xlsxpart = MIMEApplication(open(xlsxfile, 'rb').read())
xlsxpart.add_header('Content-Disposition', 'attachment', filename=xlsxfile[1:])
msg.attach(xlsxpart)
shutil.move(xlsxfile, './sent/'+xlsxfile[2:])
try:
client = smtplib.SMTP()
client.connect('XX.XXX.XX.XX', port=25)
client.sendmail(username, rcptlist, msg.as_string())
client.quit()
#...exception handling
for xlsxfile in glob.glob(os.path.join('.', 'START_OF_FILENAME_*.XLSX')):
...
msg.attach(xlsxpart)
...
在每次迭代中,当前文件都被添加到现有的 msg
对象中。当循环进行到第三次迭代时,msg
已经附加了前 2 个文件。
相反,每次迭代都应创建一个新的 msg
对象:
for xlsxfile in glob.glob(os.path.join('.', 'START_OF_FILENAME_*.XLSX')):
...
msg = Message(...) # however you created msg before the loop
msg.attach(xlsxpart)
...