


Python automated office Excel splits and automatically sends emails
需求
需要向大约 500 名用户发送带有 Excel 附件的电子邮件,同时必须按用户从主 Excel 文件中拆分数据以创建他们自己的特定文件,然后将该文件通过电子邮件发送给正确的用户
需求解析
大致的流程就是上图,先拆分 Excel 数据,提取出对应的邮件地址和用户的数据信息,再自动添加到邮件的附件当中
代码实现
首先我们先来看下我们手中 Excel 的数据形式是怎么样的。
import datetime import os import shutil from pathlib import Path import pandas as pd src_file = Path.cwd() / 'data' / 'Example4.xlsx' df = pd.read_excel(src_file) df.head()
可以看出,CUSTOMER_ID 就是那个唯一的用户 ID,下面我们以该字段来分组,得到如下数据。
customer_group = df.groupby('CUSTOMER_ID') for ID, group_df in customer_group: print(ID) >>>Output>>> A1000 A1001 A1002 A1005 ...
我们再来看下用户 A1005 所对应的数据形式。
接下来我们就为每一个用户创建一个 Excel,后面就可以作为附件使用。
attachment_path = Path.cwd() / 'data' / 'attachments' today_string = datetime.datetime.today().strftime('%m%d%Y_%I%p') attachments = [] for ID, group_df in customer_group: attachment = attachment_path / f'{ID}_{today_string}.xlsx' group_df.to_excel(attachment, index=False) attachments.append((ID, str(attachment)))
我们来看下变量 attachments 所包含的数据吧。
[('A1000', 'c:\Users\luobo\notebooks\2020-10\data\attachments\A1000_01162021_12PM.xlsx'), ('A1001', 'c:\Users\luobo\notebooks\2020-10\data\attachments\A1001_01162021_12PM.xlsx'), ('A1002', 'c:\Users\luobo\notebooks\2020-10\data\attachments\A1002_01162021_12PM.xlsx'), ('A1005', 'c:\Users\luobo\notebooks\2020-10\data\attachments\A1005_01162021_12PM.xlsx')]
最后我们可以通过将 DataFrame 合并在一起来生成带有电子邮件地址的文件列表。
email_merge = pd.merge(df, df2, how='left') combined = email_merge[['CUSTOMER_ID', 'EMAIL', 'FILE']].drop_duplicates()
得到的 DataFrame 如下:
我们已经收集了客户名单、他们的电子邮件和附件,现在我们就可以用 Outlook 发送一封电子邮件了。
import win32com.client as win32 today_string2 = datetime.datetime.today().strftime('%b %d, %Y') 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 = today_string2 + ' Report' mail.Body = """Please find today's report attached.""" mail.Attachments.Add(Source=attachment_path) # Use this to show the email #mail.Display(True) # Uncomment to send #mail.Send()
通过上面这个简单的类,我们可以生成电子邮件并附加 Excel 文件。
同时我们还注意到,这里使用了 win32,关于这个库的具体使用,我们在下次的文章中再具体说明吧。
email_sender = EmailsSender() for index, row in combined.iterrows(): email_sender.send_email(row['EMAIL'], row['FILE'])
最后,我们再把所有生成的 Excel 存档,以备后面审查、比对等。
archive_dir = Path.cwd() / 'archive' for f in attachments: shutil.move(f[1], archive_dir)
至此,我们的编码结束,整体来看还是比较简单的。
The above is the detailed content of Python automated office Excel splits and automatically sends emails. For more information, please follow other related articles on the PHP Chinese website!

ThedifferencebetweenaforloopandawhileloopinPythonisthataforloopisusedwhenthenumberofiterationsisknowninadvance,whileawhileloopisusedwhenaconditionneedstobecheckedrepeatedlywithoutknowingthenumberofiterations.1)Forloopsareidealforiteratingoversequence

In Python, for loops are suitable for cases where the number of iterations is known, while loops are suitable for cases where the number of iterations is unknown and more control is required. 1) For loops are suitable for traversing sequences, such as lists, strings, etc., with concise and Pythonic code. 2) While loops are more appropriate when you need to control the loop according to conditions or wait for user input, but you need to pay attention to avoid infinite loops. 3) In terms of performance, the for loop is slightly faster, but the difference is usually not large. Choosing the right loop type can improve the efficiency and readability of your code.

In Python, lists can be merged through five methods: 1) Use operators, which are simple and intuitive, suitable for small lists; 2) Use extend() method to directly modify the original list, suitable for lists that need to be updated frequently; 3) Use list analytical formulas, concise and operational on elements; 4) Use itertools.chain() function to efficient memory and suitable for large data sets; 5) Use * operators and zip() function to be suitable for scenes where elements need to be paired. Each method has its specific uses and advantages and disadvantages, and the project requirements and performance should be taken into account when choosing.

Forloopsareusedwhenthenumberofiterationsisknown,whilewhileloopsareuseduntilaconditionismet.1)Forloopsareidealforsequenceslikelists,usingsyntaxlike'forfruitinfruits:print(fruit)'.2)Whileloopsaresuitableforunknowniterationcounts,e.g.,'whilecountdown>

ToconcatenatealistoflistsinPython,useextend,listcomprehensions,itertools.chain,orrecursivefunctions.1)Extendmethodisstraightforwardbutverbose.2)Listcomprehensionsareconciseandefficientforlargerdatasets.3)Itertools.chainismemory-efficientforlargedatas

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
