質問

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

役に立ちましたか?

解決 2

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...

他のヒント

You could generate the email content to send using email package (from stdlib) e.g.:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from cgi import escape
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from smtplib import SMTP_SSL

login, password = 'me@example.com', 'my password'

# create message
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('subject…', 'utf-8')
msg['From'] = login
msg['To'] = ', '.join([login,])

# Create the body of the message (a plain-text and an HTML version).
text = "Hello,\nFollowing is the message\n%(somelist)s\n\nThank you." % dict(
    somelist='\n'.join(["- " + item for item in mail_body]))

html = """<!DOCTYPE html><title></title><p>Hello,<p>Following is the message 
<ul>%(somelist)s</ul><p>Thank you. """ % dict(
    somelist='\n'.join(["<li> " + escape(item) for item in mail_body]))

# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(MIMEText(text, 'plain', 'utf-8'))
msg.attach(MIMEText(html, 'html', 'utf-8'))    

# send it
s = SMTP_SSL('smtp.mail.example.com', timeout=10) # no cert check on Python 2

s.set_debuglevel(0)
try:
    s.login(login, password)
    s.sendmail(msg['From'], msg['To'], msg.as_string())
finally:
    s.quit()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top