Search code examples
pythonsmtplib

Python HTML Email : How to insert list items in HTML email


I tried hard to find solution to this issues but all in vein, finally i have to ask you guys. I have HTML email (using Python's smtplib). Here is the code

Message = """From: abc@abc.com>
To: abc@abc.com>
MIME-Version: 1.0
Content-type: text/html
Subject: test

Hello,
Following is the message 
""" + '\n'.join(mail_body)  + """
Thank you.
"""

In above code, mail_body is a list which contains lines of output from a process. Now what i want is, to display these lines (line by line) in HTML email. What is happening now its just appending line after line. i.e.

I am storing the output(of process) like this :

for line in cmd.stdout.readline()
    mail_body.append()

Current Output in HTML email is:

Hello,
abc
Thank you.

What i want :

Hello,
a
b
c
Thank you.

I just want to attach my process output in HTML email line by line. Can my output be achieved in any way?

Thanks and Regards


Solution

  • in HTML, a new line is not \n it is <br> for "line break" but since you are also not using HTML tags in this email, you also need to know that in MIME messages, a newline is \r\n and not just \n

    So you should write:

    '\r\n'.join(mail_body)
    

    For newlines that deal with the MIME message, but if you are going to use the HTML for formatting, then you need to know that <br> is the line break, and it would be:

    '<br>'.join(mail_body)
    

    To be comprehensive, you could try:

    '\r\n<br>'.join(mail_body) 
    

    But I do now know what that would like like...