0

I'm using Flask to generate API and passing the data using rendered template to create charts on html page using py-script.

Please let me know how can I send the rendered html page with all charts over email?

At least if I get an idea to store the rendered html page will also work.

def test():
    try:
        df = {'C': 20, 'C++': -15, 'Java': 30,
                'Python': 35}

        cars = ['AUDI', 'BMW', 'FORD', 'TESLA', 'JAGUAR', 'MERCEDES']
        point = [23, 17, 35, 29, 12, 41]

        #df1 = pd.DataFrame(list(zip(cars, point)), columns=['cars', 'point'])
        # showing the prediction results in a UI

        return render_template('test.html',data=df,ct=cars,pt=point)



    except Exception as e:
        print('The Exception message is: ',e)
        logging.debug(e)
        return 'something is wrong'

Test.html

<!DOCTYPE html>
<html>
  <head>
      <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
      <script defer src="https://pyscript.net/alpha/pyscript.js"></script>

      <py-env>
        - pandas
        - numpy
        - matplotlib
      </py-env>
  </head>
  <body>

<py-script>
import matplotlib.pyplot as plt

y = list({{data}}.keys())
x = list({{data}}.values())

plt.barh(y, x, color=['red', 'green', 'blue', 'cyan'])

# setting label of y-axis
plt.ylabel("pen sold")

# setting label of x-axis
plt.xlabel("price")
plt.title("Horizontal bar graph")
plt

</py-script>

  </body>
</html>

Regards, Rohan

Rohan Waje
  • 25
  • 6

1 Answers1

0

From the documentation: flask.render_template(template_name_or_list, **context)

Renders a template from the template folder with the given context.

This means that through the render_template function you are able to generate a string starting from a file (the template) and any parameters passed to the template.

Instead of returning the result of the render_template, save it in a variable and then send the content via email.

def test():
    try:
        df = {'C': 20, 'C++': -15, 'Java': 30,
                'Python': 35}

        cars = ['AUDI', 'BMW', 'FORD', 'TESLA', 'JAGUAR', 'MERCEDES']
        point = [23, 17, 35, 29, 12, 41]

        #df1 = pd.DataFrame(list(zip(cars, point)), columns=['cars', 'point'])
        # showing the prediction results in a UI

        my_html = render_template('test.html',data=df,ct=cars,pt=point)
        send_mail("test@test.com", "subject", my_html)


    except Exception as e:
        print('The Exception message is: ',e)
        logging.debug(e)
        raise e

Note that if the template contains css files served by your own application, for example: <link rel = "stylesheet" href = "{{url_for ('static', filename = 'style.css')}}">, the email will be displayed correctly only if your application It is running. Otherwise embed the css directly into the template, which I recommend if your purpose is to generate an email.

Matteo Pasini
  • 1,787
  • 3
  • 13
  • 26
  • I did try with your suggestions but unable to achieve the end result as getting error. It would be great help if you can provide code for send_mail() function. Please find error: * Debug mode: on, The Exception message is: [Errno 2] No such file or directory: ' \n\n \n – Rohan Waje May 20 '22 at 09:53
  • [take a look here](https://stackoverflow.com/questions/882712/send-html-emails-with-python). The error you posted in the comment refers to a method that takes the path of a file as a parameter, but you are passing it a string containing some html. – Matteo Pasini May 20 '22 at 10:00
  • I tried to send my_html variable via email it is getting sent but body is containing the html code stored in my_html. If I save that email body manually to .html file I am getting desired output. – Rohan Waje May 20 '22 at 10:59