[英]Python send emails with corresponding attachments
I have a desktop folder with 3 XLSX files: ID1.xlsx
, ID2.xlsx
, ID3.xlsx
我有一个包含 3 个 XLSX 文件的桌面文件夹:
ID1.xlsx
、 ID2.xlsx
、 ID3.xlsx
I can use the following code to loop through a list of 3 email addresses and send individual emails to each address, but it attaches all XLSX files in the folder.我可以使用以下代码循环遍历 3 个电子邮件地址的列表并向每个地址发送单独的电子邮件,但它会附加文件夹中的所有 XLSX 文件。
Expected Result: I want to attach ID1.xlsx
to the first email and send, ID2.xlsx
to the 2nd email and send, and finally ID3.xlsx
to the 3rd email and send.预期结果:我想将
ID1.xlsx
附加到第一封电子邮件并发送, ID2.xlsx
到第二封电子邮件并发送,最后将ID3.xlsx
到第三封电子邮件并发送。
email_addresses = ['test1@test.com', 'test2@test.com', 'test3@test.com']
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, Type=olByValue)
mail.Send()
def send_emails(self, email_addresses, attachment_path=None):
for email in email_addresses:
self.send_email(email, attachment_path)
attachment_path = r'C:\Users\Desktop\Test\*.xlsx'
email_sender = EmailsSender()
email_sender.send_emails(email_addresses, attachment_path)
You will need to reference the file name with email so switch to Dictionaries .您需要使用电子邮件引用文件名,因此请切换到Dictionaries 。
Example例子
email_addresses = {'test1@test.com': 'ID1.xlsx',
'test2@test.com': 'ID2.xlsx',
'test3@test.com': 'ID3.xlsx'
}
attachment_path = r'C:\Users\Desktop\Test'
for email, file in email_addresses.items():
print(email, attachment_path + file)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.