generating emails group by tuple values python
Question: I have a tuple in the format (Name, email, units sold). I would like to
generate an HTML table, grouped by Name and then embed that table into an
email through Outlook.

My Code:

    
    
    from itertools import groupby
    from operator import itemgetter
    import win32com.client
    
    mytuple = [('Andrew','Andrew@gmail.com','20'),('Jim',"Jim@gmail.com",'12'),("Sarah","Sarah@gmail.com",'43'),("Jim","Jim@gmail.com",'15'),("Andrew","Andrew@gmail.com",'56')]
    mytuple = sorted(mytuple)
    FULL_HTML = []
    
    for name, rows in groupby(mytuple, itemgetter(0)):
         table = []
         for name, value2 in rows:
            table.append(
                "<tr><td>{}</td><td>{}</td></tr>".format(
                    name, value2 ))
    
         html_code = "<html><table>" + str(table) + "</table></html>"
    
         olMailItem = 0x0
         obj = win32com.client.Dispatch("Outlook.Application")
         newMail = obj.CreateItem(olMailItem)
         newMail.Subject = "This is the subject"
         newMail.HTMLBody = html_code
         newMail.To  = "sampleemail@gmail.com"
         newMail.Display()
    

Desired output:

This would open 3 emails with HTML code in their body.

Email 1:

    
    
    <html>
    <table>
    <tr><td>Andrew</td><td>20</td><td></tr>
    <tr><td>Andrew</td><td>56</td><td></tr>
    </table>
    </html>
    

Email 2:

    
    
    <html>
    <table>
    <tr><td>Jim</td><td>12</td><td></tr>
    <tr><td>Jim</td><td>15</td><td></tr>
    </table>
    </html>
    

Email 3:

    
    
    <html>
    <table>
    <tr><td>Sarah</td><td>43</td><td></tr>
    </table>
    </html>
    


Answer: Here's your problem:

    
    
    for name, value2 in rows:
        table.append(
            "<tr><td>{}</td><td>{}</td></tr>".format(
                name, value2 ))
    

Change this to:

    
    
    for n, e, id in rows:
        table.append(
            "<tr><td>{}</td><td>{}</td></tr>".format(
                n, id ))
    
    html_code = "<html><table>" + ''.join(table) + "</table></html>"
    

The groupby function still returns 3-tuples.

