0

I am trying to send an email using python. I am trying to format my email in HTML format. Below is the code:-

sender = '[email protected]'
receivers = ['[email protected]']
message = message = """From: team <[email protected]>
To: To Person <[email protected]>
MIME-Version: 1.0
Content-type: text/html
Subject: Daily Report 
<html>
<table>
Report
<% for i in rows: %>
    <tr>
        <td> <%= rows[0][1] %>
    </tr>
<% end %>
</table>

<b>This is HTML message.</b>
<h1>This is headline.</h1>
</html>
"""
smtpObj = smtplib.SMTP('SMTP mailer')
smtpObj.sendmail(sender, receivers, message)

I am fetching rows from Database based on some condition and storing it in "rows" variable. I am trying to loop the HTML table creation based on the number of rows returned.

Whenever i send an email it does not identify the for loop that i have written. It does identify the "This is HTML message" in Bold form and "This is headline" in H1 format

What am i doing wrong?

1 Answer 1

2

You want to use a template engine for creating the HTML. For Python the message string you are using is just a string, nothing else. The `<% for i in rows: %>' is this very text, Python does no processing whatsoever with it.

Your mail message is not correctly formatted according to RFC2822:

  • You must use CRLF ('\r\n') as newline separators, LF (\n') only is illegal
  • Headers and body must be separated by a CRLF (i.e. one empty line).

For sending an HTML formatted message with Python, I would suggest that you use the features from email.mime, c.f. How to send an email with style in Python3?

Sign up to request clarification or add additional context in comments.

1 Comment

Ok. I would be using Jinja2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.