Search code examples
pythonjsonloopssmtplib

Send loop result within email body


I'm trying to present "print" result (example 1) in content of email (example 2).

Data I use:

 {
  "@odata.context": "XXX",
  "value": [
    {
      "Customer_Name": "ABC inc",
      "Customer_No": "002",
      "Date_of_Export": "2020-01-10T05:36:55.3Z",
      "Error_Message": "error message 1.",
      "Type_of_Export": "E-Mail"
    },
    {
      "Customer_Name": "CBA inc",
      "Customer_No": "001",
      "Date_of_Export": "2020-01-10T05:39:13.137Z",
      "Error_Message": "Error message 2",
      "Type_of_Export": "E-Mail"
    }
  ]}

EXAMPLE 1 (PRINT):

When I use below code I get desired result printed:

r = requests.get("http://www.example.com/test.json")
r_dict = json.loads(r.text)

if len(r_dict["value"])==0:
    print("No errors")
else:
    print("List of errors:\n")
    for item in r_dict["value"]:
        print('"Customer":', '(' + item['Customer_No'] + ')' + item['Customer_Name'] + ', "Typ":', item['Type_of_Export'] + ', "Error": ', item['Error_Message'])

I get:

List of errors:

"Customer": (002)ABC inc, "Typ": E-Mail, "Error": error message 1.
"Customer": (001)CBA inc, "Typ": E-Mail, "Error": Error message 2

EXAMPLE 2 (MAIL):

But i can't get that right to send same result within email body, because only last line is enclosed

List of errors:

"Customer": (001)CBA inc, "Typ": E-Mail, "Error": Error message 2

Code I use:

import json
import requests
import smtplib
from requests_ntlm import HttpNtlmAuth
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

html_top = """<html><body>"""
html_end = """</body></html> """

r = requests.get("http://www.example.com/test.json")
r_dict = json.loads(r.text)

    if len(r_dict["value"])==0:
        print("No errors")
    else:
            html_body_top = "<p>List of errors:<br></p>"

            for item in r_dict["value"]:
                html_body = '"Customer":' + '(' + item['Customer_No'] + ')' + item['Customer_Name'] + ', "Typ":' + item['Type_of_Export'] + ', "Error": ' + item['Error_Message']
            mail_html = MIMEText(html_top + html_body_top + html_body + html_end, "html")
            message.attach(mail_html)
            with smtplib.SMTP("000.000.000.000", xx) as server:
                    server.sendmail(sender_email, receiver_email, message.as_string())

I would like to send email containing all 2 lines, just like in example 1.


Solution

  • Your problem is that each time this loop iterate you are overwriting the previous value of html_body

    for item in r_dict["value"]:
                    html_body = '"Customer":' + '(' + item['Customer_No'] + ')' + item['Customer_Name'] + ', "Typ":' + item['Type_of_Export'] + ', "Error": ' + item['Error_Message']
    

    A quick solution is to change to using the += operator and add a new line character on the end.

    html_body = ''
    for item in r_dict["value"]:
                    html_body += '"Customer":' + '(' + item['Customer_No'] + ')' + item['Customer_Name'] + ', "Typ":' + item['Type_of_Export'] + ', "Error": ' + item['Error_Message'] + '\n'