python - Create a for loop that generates individual emails with html dataframe for each unique recipient
问题描述
I want to create a for loop that creates individual emails with html dataframe for each unique recipient (using the first column).
the dataframe looks like this:
Expected output:
My current code:
for index, row in df.iterrows():
email = (row['Email Address'])
subject = (row['Subject'])
table = df.iloc[:, 2:].to_html(index = False)
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = subject
newMail.HTMLbody = ( '''
<html>
<head>
</head>
<body>
<p>Hi All,</p>
<p>{TABLE}</p>
<p>Best Regards,</p>
</body>
</html>'''.format(TABLE = table))
newMail.To = email
newMail.display()
解决方案
要按唯一电子邮件对表格进行分组,您需要使用 groupby:
grp = df.groupby('email') #group data by email
sent_mail = [] #store emails to which messages have been sent here
for index, row in df.iterrows():
if row['email'] in sent_mail: #check if mail has already been sent to prevent sending multile mails
pass
else:
email = (row['email'])
sent_mail.append(email)
subject = (row['subject'])
table = grp.get_group(email).to_html(index = False)
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = subject
newMail.HTMLbody = ( '''
<html>
<head>
</head>
<body>
<p>Hi All,</p>
<p>{TABLE}</p>
<p>Best Regards,</p>
</body>
</html>'''.format(TABLE = table))
newMail.To = email
newMail.display()
推荐阅读
- javascript - javascript - 如何“连接”属性
- javascript - 如何将本地存储中的输入分组为一个按我的日期时间输入分类的“事件”
- c# - 使用 cookie 身份验证为 REST 服务设置 MSTest 的最佳方法?
- django - 如何将一个模型的主键传递到另一个模型的表单字段中?
- python - 使用 tkinter 将文件路径保存在变量中
- javascript - Passport.js 通过 Post 请求获取当前登录的用户
- javascript - 尝试通过选择“是”的 # 个答案来更新总列
- telegram - 如何使用电报机器人python的内联键盘将单击的按钮存储为字符串
- c++ - 卸载 dll 会引发访问冲突错误
- mysql - 从存储过程更新字段