使用Python Dict发送带有特定附件的电子邮件
我有一本python字典:使用Python Dict发送带有特定附件的电子邮件,python,outlook,attachment,win32com,Python,Outlook,Attachment,Win32com,我有一本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.x
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
附加到第三个电子邮件地址并发送
以下代码生成错误“未定义名称‘文件’”。为了获得上述预期结果,我遗漏了什么
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)
到
解释者抱怨,因为
文件
未在此处声明。对象电子邮件组
包含什么?正如错误所示,什么是文件
?抱歉-我更正了问题。电子邮件组是电子邮件地址和相应附件的目录。文件是在桌面文件夹中找到的文件。哪一行导致错误?我假设发送电子邮件给发件人。发送电子邮件(电子邮件组、附件路径+文件)
。你想在这里干什么?当这行执行时,没有名为file
的变量。我试图使用带有电子邮件地址和文件名的dict“email_group”将正确的XLSX文件附加到正确的电子邮件地址并发送电子邮件。我已对您下面的回答作出了响应。我进行了您建议的更改,并收到以下错误:“(-2147352567,‘发生异常’,(4096,‘Microsoft Outlook’,‘找不到此文件。请验证路径和文件名是否正确。”,无,0,-2147024894),无”@标记错误非常清楚你需要做什么我真的无法理解。我试图编辑附件路径以包含*.xlsx,但没有成功。如果您能提供任何帮助,我们将不胜感激@标记您应该通过添加print()
语句来调试代码。例如,在发送电子邮件()
添加打印(附件路径+文件)
。查看您试图附加到电子邮件的实际路径。仔细检查此输出是否拼写错误或缺少斜杠。您还应该签出os.path.join()
方法,以确保正确添加斜杠。如果您仍然需要帮助,请发布一个新问题,因为我在这里的回答解决了您最初在此页面上发布的问题。
email_sender.send_emails(email_group, attachment_path)