python-3.x - 使用 Pandas 数据框中的唯一值从 python 发送电子邮件
问题描述
我正在尝试根据 pandas 数据框中的唯一值从 Python 发送电子邮件。我能够向单个用户触发电子邮件。当我尝试通过验证用户或团队是否存在来发送它时,它不起作用。
import smtplib
import email
import email.mime.multipart
import email.mime.text
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import pandas as pd
import numpy as np
contacts = pd.read_excel(r'C:\Contacts\Contacts.xlsx',
sheet_name = 'EMAIL',
header = 0
)
releases_data=pd.read_excel(r'C:\Hourly Releases\Releases.xlsx'
,header = 0)
team_data=pd.read_excel(r'C:\Hourly Releases\EE Details.xlsx
, header = 0)
team_data_applied=pd.merge(left=team_data,right=releases_data,on = 'Empl ID')
unique=team_data_applied['Team'].unique()
for team in unique:
manager = team_data_applied[team_data_applied['Team']==team]
subject = "#MS#"+Team+"- Hourly Releases"
body = """
Hi,
Below is the snap shot of team's hourly releases.
"""
mail_body = body + "\n"+str(manager)
MY_ADDRESS="xyz@abc.com"
PASSWORD = '******'
toaddr = "teammanager1@abc.com"
msg = MIMEMultipart()
msg['From'] = MY_ADDRESS
msg['To'] = toaddr
msg.attach(MIMEText(mail_body, 'plain'))
server = smtplib.SMTP(host='smpt-outlook.mail.com',port=25)
server.starttls()
server.login(MY_ADDRESS,PASSWORD)
text = msg.as_string()
server.sendmail(MY_ADDRESS,toaddr, text)
server.quit()
使用此代码,我可以将电子邮件触发给单个用户。我尝试创建两个函数,然后在主函数中调用它们来发送电子邮件。代码有效。没有任何电子邮件被触发。
以下是我创建的功能。
def team_content():
for team in unique:
manager =team_data_applied[team_data_applied['Team']==team]
subject = "#MS#"+Team+"- Hourly Releases"
body = """
Hi,
Below is the snap shot of team's hourly releases.
"""
mail_body = body + "\n"+str(manager)
print(mail_body)
return team,manager,mail_body,subject
def get_contacts():
contacts = pd.read_excel(r'C:\Contacts\Contacts.xlsx',
sheet_name = 'EMAIL',
header = 0
)
for index , row in contacts.iterrows():
teams = contacts['TEAM']
emails = contacts['EMAIL']
return teams, emails
def main():
team,manager,mail_body,subject =team_content()
teams, emails = get_contacts()
server = smtplib.SMTP(host='smtp-outlook.mail.com',port=25)
for team,manager,mail_body,subject in zip(team,manager,mail_body,subject):
for teams, emails in zip(teams, emails):
if team == teams:
msg.attach(MIMEText(mailbody, 'plain'))
msg['From'] = xyz@abc.com
msg['To'] = emails
msg['Subject'] = subject
text = msg.as_string()
server.sendmail('xyz@abc.com',emails, text)
server.quit()
if __name__ == '__main__':
main()
不知道要更改什么,以便我可以触发电子邮件。如果我使用单个电子邮件,效果很好。