Search code examples
pythonpandasdataframesmtplib

how to filter a DF groupby object to a list


I am filtering a dataframe and sending the results of the info in an email using smtplib. Here's what I got so far.

def SMTP_Emailer(content, receiver):
    msg = EmailMessage()
    msg['Subject'] = "Test Email!"
    msg['From'] = 'test@example.com'
    msg['To'] = [receiver]

    msg.set_content( f""" This is a test email, please disregard{content}
        """,  subtype='html')


    with smtplib.SMTP('sendsmtp.server.com', 1234) as s:
                s.send_message(msg)

I have a pandas dataframe like this:

d = 
  STATE   CUSTOMER      ORDERS     EMAIL OWNER
0    ID   Jerry         10        Jerry@example.com  
1    MT   Tom           119       Jerry@example.com
2    CA   Patrick       87        Jerry@example.com
3    WA    Lucy         918       Mark@example.com

Then Im grouping by the series d['EMAIL OWNER']

grouped = df.groupby("EMAIL TEST")
    for emails, data  in grouped:
        print(emails)
        dataframes = [emails for e, group in grouped]
        print(dataframes)
        SMTP_Emailer(data.loc[:, :].to_html(), dataframes)

Im expecting ['Jerry@example.com ', 'Mark@example.com '] so that I can put them in my msg['To']

but I'm unexpectedly getting ['Mark@example.com ','Mark@example.com '] in VS Code

and in jupyter notebook I'm getting:

Mark@example.com
['Mark@example.com', 'Mark@example.com']
Jerry@example.com
['Jerry@example.com', 'Jerry@example.com']

Result outcome is 2 separate emails to occur. I used the groupby to filter from the main data source(d) by the persons email address so that they'd only see what was owned by them and not the other person. So Mark wouldnt see Jerry's data (and the other way around)

Let me know if this helps clarify things.

#Email 1  gets sent to Jerry@example.com

Email 1 = 
 
  STATE   CUSTOMER      ORDERS     EMAIL OWNER
0    ID   Jerry         10        Jerry@example.com  
1    MT   Tom           119       Jerry@example.com
2    CA   Patrick       87        Jerry@example.com

#Email 2  gets sent to Mark@example.com

Email 2 =

3   WA    Lucy         918       Mark@example.com

Solution

  • Glad you solved your problem! I just wanted to show how you could have used groupby if you were still interested. In your answer you pretty much made a groupby (!):

    for email,dfuser in df.groupby('EMAIL OWNER'):
        SMTP_Emailer(dfuser.to_html(), email)