Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
730 views
in Technique[技术] by (71.8m points)

email - How to get line breaks in e-mail sent using Python's smtplib?

I have written a script that writes a message to a text file and also sends it as an email. Everything goes well, except the email finally appears to be all in one line.

I add line breaks by and it works for the text file but not for the email. Do you know what could be the possible reason?


Here's my code:

import smtplib, sys
import traceback
def send_error(sender, recipient, headers, body):

    SMTP_SERVER = 'smtp.gmail.com'
    SMTP_PORT = 587
    session = smtplib.SMTP('smtp.gmail.com', 587)
    session.ehlo()
    session.starttls()
    session.ehlo
    session.login(sender, 'my password')
    send_it = session.sendmail(sender, recipient, headers + "

" +  body)
    session.quit()
    return send_it


SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = 'sender_id@gmail.com'
recipient = 'recipient_id@yahoo.com'
subject = 'report'
body = "Dear Student, 
 Please send your report
 Thank you for your attention"
open('student.txt', 'w').write(body) 

headers = ["From: " + sender,
               "Subject: " + subject,
               "To: " + recipient,
               "MIME-Version: 1.0",
               "Content-Type: text/html"]
headers = "
".join(headers)
send_error(sender, recipient, headers, body)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unfortunately for us all, not every type of program or application uses the same standardization that python does.

Looking at your question i notice your header is: "Content-Type: text/html"

Which means you need to use HTML style tags for your new-lines, these are called line-breaks. <br>

Your text should be:

"Dear Student, <br> Please send your report<br> Thank you for your attention"

If you would rather use character type new-lines, you must change the header to read: "Content-Type: text/plain"

You would still have to change the new-line character from a single to the double which is used in email.

Your text would be:

"Dear Student, 
 Please send your report
 Thank you for your attention"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...