【问题标题】:Send Outlook Emails with attachments in Python (pywin32)在 Python (pywin32) 中发送带有附件的 Outlook 电子邮件
【发布时间】:2021-04-30 21:02:27
【问题描述】:

我正在尝试使用库 pywin32 在 Python 中编写 Outlook 电子邮件。我有一个数据框,其中包含一些收件人的电子邮件和附件路径。我想知道如何在每个唯一收件人下添加所有附件?

print(my_df)

Receiver_Email             Attachment_Path                          HTMLBody
john.doe@gmail.com         C:/Users/Desktop/Attachment1.pdf        HTMLBODY_1
john.doe@gmail.com         C:/Users/Desktop/Attachment2.pdf        HTMLBODY_1
john.doe@gmail.com         C:/Users/Desktop/Attachment3.pdf        HTMLBODY_1
sean.smith@hotmail.com     C:/Users/Desktop/Attachment11.pdf       HTMLBODY_2
sean.smith@hotmail.com     C:/Users/Desktop/Attachment22.pdf       HTMLBODY_2
sean.smith@hotmail.com     C:/Users/Desktop/Attachment33.pdf       HTMLBODY_2

我的代码如下所示:

for index, row in my_df.iterrows():
    outlook = client.Dispatch('Outlook.Application')
    mail = outlook.CreateItem(0)
    mail.To = row['Receiver_Email']
    mail.Subject = 'Greetings from Here!'
    mail.Body = 'Please find your attachment(s)'
    mail.Attachments.Add(row['Attachment_Path'])
    mail.HTMLBody = row['HTMLBODY']
    mail.Send()

但是,这将向 john.doe@gmail.com 发送 3 封电子邮件,向 sean.smith@hotmail.com 发送 3 封电子邮件。我的预期输出是总共发送 2 封电子邮件(约翰 1 封,肖恩 1 封),每封包含 3 个附件。

有没有办法做到这一点?感谢您的帮助!

【问题讨论】:

    标签: python pandas email pywin32


    【解决方案1】:

    对电子邮件地址执行groupby,这会创建唯一的数据框,然后迭代邮件附件。这样的事情应该可以工作:

    GB = my_df.groupby("Receiver_Email")
    for ID , DF in GB:
        outlook = client.Dispatch('Outlook.Application')
        mail = outlook.CreateItem(0)
        mail.To = row['Receiver_Email']
        mail.Subject = 'Greetings from Here!'
        mail.Body = 'Please find your attachment(s)'
        for id , row in DF.iterrows():
            mail.Attachments.Add(row['Attachment_Path'])
        mail.Send()
    

    【讨论】:

    • 谢谢@Q-man;它奏效了,这正是我所需要的!
    • 如果我想将 HTMLBODY 添加到每个收件人的电子邮件中,我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 2017-02-04
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 2014-08-03
    • 2015-09-09
    相关资源
    最近更新 更多