【问题标题】:How to send parts of dataframe to corresponding email that is in a same dataframe如何将部分数据帧发送到同一数据帧中的相应电子邮件
【发布时间】:2020-04-17 15:16:28
【问题描述】:

我有一个数据框,其中包含 email 列和其他列。

我需要将此数据发送到相应的电子邮件,例如第0行需要通过电子邮件发送到Tony@mail.com, 第 1 行需要通过电子邮件发送至Sergio@mail.com,第 2 行和第 3 行需要发送至Nico@mail.com

     Name            Email      Subject CreatedDate     DueDate FinalDeadLine
0    Tony    Tony@mail.com      Renewal  2019-12-15  2019-12-16    2019-12-25
1  Sergio  Sergio@mail.com  NewBusiness  2019-11-18  2019-11-22    2019-11-28
2    Nico    Nico@mail.com  Endorsement  2019-12-11  2019-12-13    2019-12-24
3    Nico    Nico@mail.com      Rewrite  2019-12-05  2019-12-07    2019-12-23

使用Splitting dataframe into multiple dataframes 我正在对数据框执行视图:

示例代码:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import pandas as pd

df = pd.DataFrame({
                'Name': ['Tony','Sergio','Nico','Nico']
                ,'Email': ['Tony@mail.com', 'Sergio@mail.com','Nico@mail.com','Nico@mail.com']
                ,'Subject':['Renewal', 'NewBusiness', 'Endorsement','Rewrite']
                ,'CreatedDate': ['2019-12-15','2019-11-18','2019-12-11','2019-12-05']
                ,'DueDate': ['2019-12-16','2019-11-22','2019-12-13','2019-12-07']
                ,'FinalDeadLine': ['2019-12-25','2019-11-28','2019-12-24','2019-12-23']
                })
print(df)

# sort the dataframe
# the parameter axis=1 refer to columns, while 0 refers to rows
df.sort_values(by='Email', axis=0, inplace=True)

# set the index to be this and don't drop
df.set_index(keys=['Email'], drop=False,inplace=True)

# get a list of emails
email_list=df['Email'].unique().tolist()

# now we can perform a lookup on a 'view' of the dataframe
nico = df.loc[df.Email=='Nico@mail.com']

# itrating through email_list and printing dataframe corresponding to each email
for e in email_list:
  d = df.loc[df.Email==e]
  #print(d)

但是我怎样才能将它连接到我的send_mail 函数呢?

发送邮件功能:

user = "myemail@gmail.com"
pwd = "mypassword"
subject = "Test subject"
recipients = "recipients@gmail.com"

def send_email(user,pwd, recipients, subject):
    try:
        df_html = df.to_html()
        dfPart = MIMEText(df_html,'html')
    #Container
        msg = MIMEMultipart('alternative')
        msg['Subject'] = subject
        msg['From'] = user
        msg['To'] = ",".join(recipients)
        msg.attach(dfPart)

        server = smtplib.SMTP('smtp.gmail.com: 587')
        server.starttls()
        server.login(user, pwd)

        server.sendmail(user, recipients, msg.as_string())
        server.close()
        print("Mail sent succesfully!")
    except Exception as e:
        print(str(e))
        print("Failed to send email")
send_email(user,pwd,recipients,"Test Subject")

或者也许有更好、最有效的方法来完成这一切? 网上有什么好的例子吗?

【问题讨论】:

    标签: python python-3.x pandas smtp


    【解决方案1】:

    因此,一旦您完成了对数据框的操作......您可以使用 apply 函数进行逐行操作

    轴 = 1

    下面是一个例子..

    import pandas as pd
    
    
    df = pd.DataFrame()
    df["A"] = [1,2,3,4,5]
    df["B"] = ["A", "B", "C", "D", "E"]
    
    # print (df)
    
    def printA(d):
        print("row A", d["A"], "row B", d["B"])
    
    df.apply(lambda x:printA(x), axis=1)
    
    row A 1 row B A
    row A 2 row B B
    row A 3 row B C
    row A 4 row B D
    row A 5 row B E
    

    来到你的代码。 修改电子邮件函数以接受一行作为输入。

    def send_email(用户、密码、收件人、主题):

    会变成

    def send_email(dataFrameRow):

    然后在该函数中,您可以使用相同的列名访问每一列..

    dataFrameRow["Name"] , dataFrameRow["Subject"], dataFrameRow["Email"]
    

    调用函数就像......你可以在排序后或 set_index 后调用它...... 我不确定你想在那里实现什么..但这应该适用于你的代码。

    df.apply(lambda x: send_email(x), axis=1)

    【讨论】:

    • @Serdia 让我知道您是否希望我详细说明您的特定代码.. 或者您可以从这里管理..
    • 谢谢,但很抱歉,我将如何以及在哪里实施您的解决方案来解决我的问题?
    • @Serdia 您需要将电子邮件发送到曾经的电子邮件 ID 对吗?
    • 是的,我需要向每个电子邮件 ID 发送一封包含数据框中相应数据的电子邮件
    • 您可能可以在设置索引之后调用该函数..之后我看不到任何有用的操作..
    【解决方案2】:
        from email.mime.text import MIMEText
    from email.mime.application import MIMEApplication
    from email.mime.multipart import MIMEMultipart
    from email.mime.base import MIMEBase
    from email import encoders
    from smtplib import SMTP
    import smtplib
    import sys
    import pandas as pd
    
    df = pd.DataFrame({
                    'Name': ['Tony','Sergio','Nico','Nico']
                    ,'Email': ['Tony@mail.com', 'Sergio@mail.com','Nico@mail.com','Nico@mail.com']
                    ,'Subject':['Renewal', 'NewBusiness', 'Endorsement','Rewrite']
                    ,'CreatedDate': ['2019-12-15','2019-11-18','2019-12-11','2019-12-05']
                    ,'DueDate': ['2019-12-16','2019-11-22','2019-12-13','2019-12-07']
                    ,'FinalDeadLine': ['2019-12-25','2019-11-28','2019-12-24','2019-12-23']
                    })
    print(df)
    
    df.sort_values(by='Email', axis=0, inplace=True)
    
    df.set_index(keys=['Email'], drop=False,inplace=True)
    
    email_list=df['Email'].unique().tolist()
    
    for e in email_list:
        d = df.loc[df.Email==e]
        d.to_csv('Test.csv')
        
        email_user = 'mymail@gmail.com'
        email_password = 'XXXXXXXXXX'
        
        col_one_list = [e]
        recipients = col_one_list
        
        emaillist = [elem.strip().split(',') for elem in recipients]
        msg = MIMEMultipart()
        
        msg['Subject'] = 'Test'
        msg['From'] = 'mymail@gmail.com'
        
        filename = "Test.csv"
        attachment = open("Test.csv","rb")
        part = MIMEBase('application', 'octet-stream')
        part.set_payload((attachment).read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition',"attachment; filename=%s" % filename)
        
        msg.attach(part)
        
        server = smtplib.SMTP('smtp.gmail.com: 587')
        server.starttls()
        server.login(email_user,email_password)
        server.sendmail(msg['From'], emaillist , msg.as_string())
        server.quit()
        
    print('Done')
    

    【讨论】:

      猜你喜欢
      • 2013-11-09
      • 1970-01-01
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2014-03-05
      • 2019-05-06
      相关资源
      最近更新 更多