【问题标题】:Using Python Dict to Send Emails with Specific Attachments使用 Python Dict 发送带有特定附件的电子邮件
【发布时间】:2020-08-28 14:49:30
【问题描述】:

我有一本 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 附加到第三个电子邮件地址,然后发送。

以下代码产生错误“名称'文件'未定义”。为了获得上述预期结果,我缺少什么?

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_group 包含什么?同样正如错误所暗示的那样,file 是什么?
  • 道歉 - 我更正了这个问题。 email_group 是电子邮件地址和相应附件的字典。 File 是在桌面文件夹中找到的文件。
  • 哪一行导致错误?我假设email_sender.send_emails(email_group, attachment_path + file)。你想在这里做什么?此行执行时没有名为file 的变量。
  • 我试图使用带有电子邮件地址和文件名的 dict 'email_group' 将正确的 XLSX 文件附加到正确的电子邮件地址并发送电子邮件。我已经在下面回复了你的回答。

标签: python outlook attachment win32com


【解决方案1】:

我认为你需要改变

email_sender.send_emails(email_group, attachment_path + file)

email_sender.send_emails(email_group, attachment_path)

解释器抱怨,因为这里没有声明file

【讨论】:

  • 我进行了您建议的更改并收到以下错误:“(-2147352567,'发生异常。',(4096,'Microsoft Outlook','找不到此文件。验证路径和文件名称是正确的。', None, 0, -2147024894), None)"
  • @Mark 错误很清楚你需要做什么
  • 老实说,我无法弄清楚这一点。我试图编辑附件路径以包含 *.xlsx ,但没有成功。您能提供的任何帮助将不胜感激!
  • @Mark 你应该通过添加print() 语句来调试你的代码。例如,在send_emails() 中添加print(attachment_path + file)。查看您尝试附加到电子邮件的实际路径。仔细检查此输出是否有拼写错误或缺少斜杠。您还应该检查os.path.join() 方法以确保正确添加斜线。如果您仍然需要帮助,请发布一个新问题,因为我在这里的回答解决了您最初在此页面上发布的问题。
猜你喜欢
  • 2020-09-16
  • 2014-11-09
  • 2017-02-04
  • 2019-11-21
  • 2021-12-22
  • 2015-09-09
相关资源
最近更新 更多