使用Python Dict发送带有特定附件的电子邮件

问题描述

我有一个python字典:

df.set_index('EMAIL').to_dict()['ID'] 
   
email_group = {'test1@test.com': 'ID1.xlsx','test2@test.com': 'ID2.xlsx','test3@test.com': 'ID3.xlsx'
                   }

预期结果:我想将ID1.xlsx附加到第一个电子邮件地址并发送,将ID2.xlsx附加到第二个电子邮件地址并发送,最后发送ID3.xlsx到第三个电子邮件地址并发送。

以下代码产生错误“未定义名称'file'”。我想得到上面的预期结果是什么?

class EmailsSender:
        def __init__(self):
            self.outlook = win32.Dispatch('outlook.application')
    
        def send_email(self,to_email_address,attachment_path):
            mail = self.outlook.CreateItem(0)
            mail.To = to_email_address
            mail.Subject = 'Report'
            mail.Body = """Report is attached."""
            if attachment_path:
                mail.Attachments.Add(Source=attachment_path)
            mail.Send()
    
        def send_emails(self,email_group,attachment_path=None):
            for email,file in email_group.items():
                self.send_email(email,attachment_path + file)
    
    attachment_path = r'C:\Users\Desktop\Test'
    email_sender = EmailsSender()
    email_sender.send_emails(email_group,attachment_path + file)

解决方法

我认为您需要更改

email_sender.send_emails(email_group,attachment_path + file)

email_sender.send_emails(email_group,attachment_path)

因为这里没有声明file,翻译才抱怨。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...