在浏览字典时发送电子邮件

我正在尝试发送多封电子邮件,每封电子邮件具有不同的文件附件。

像这样: file_A转到mail_a@mail.com file_B转到mail_b@mail.com ... (继续)

我尝试了这段代码,但是当我遍历字典时,我所有的电子邮件都发送到mail_c@mail.com,而不是按预期的方式从A到A,B到B,C到C。

import pandas as pd
import shutil, os
import os
import tempfile
import win32com.client as win32 
import glob, os

npath="yourpath/"

files=['file_a.xlsx','file_b.xlsx','file_c.xlsx']

mails=dict(zip(['mail_a@mail.com','mail_b@mail.com','mail_c@mail.com'],files))

for file in os.listdir(npath):
    if file.endswith(".xlsx"):
        outlook = win32.Dispatch('outlook.application')
        mail = outlook.CreateItem(0)
        for id,i in mails.items():
            mail.To = id            
        mail.Subject = 'Test'
        mail.HtmlBody = 'testing'
        mail.Attachments.Add(os.path.join(npath,file))
        mail.Display()

我很确定我的问题是循环或字典,但是尝试了几个小时后,我自己无法解决。

for id,i in mails.items():
            print(id)
            mail.To = id 
评论
  • oest
    oest 回复

    Your code should use mails dict to iterate over the list of files, here is an example:

    files=['file_a.xlsx','file_b.xlsx','file_c.xlsx']
    
    mails=dict(zip(['mail_a@mail.com','mail_b@mail.com','mail_c@mail.com'],files))
    
    for mail_id, file in mails.items():
        if file.endswith(".xlsx"):
            outlook = win32.Dispatch('outlook.application')
            mail = outlook.CreateItem(0)
            mail.To = mail_id            
            mail.Subject = 'Test'
            mail.HtmlBody = 'testing'
            mail.Attachments.Add(os.path.join(npath,file))
            mail.Display()
    

    如果您需要完全使用您的方法,则必须在第二个循环中添加文件匹配检查:

        for mail_id, file_name in mails.items():
            if file.endswith(file_name):
                mail.To = id  
                break   
    

    Note: i didn't use id as variable name because it's a reserved builtin python function

  • Gold
    Gold 回复

    您的循环返回ID的正确顺序。该词典还包含正确的键值对。您的for循环以mail_c结尾,因此被所有文件选中。

    You can fix it by bringing the mailing content/logic inside for loop

    for file in os.listdir(npath):
        if file.endswith(".xlsx"):
            outlook = win32.Dispatch('outlook.application')
            mail = outlook.CreateItem(0)
            for id,i in mails.items():
                mail.To = id            
                mail.Subject = 'Test'
                mail.HtmlBody = 'testing'
                mail.Attachments.Add(os.path.join(npath,file))
                mail.Display()