f.ashouri f.ashouri - 1 year ago 77
Python Question

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'
session = smtplib.SMTP('smtp.gmail.com', 587)
session.login(sender, 'my password')
send_it = session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
return send_it

SMTP_SERVER = 'smtp.gmail.com'
sender = 'sender_id@gmail.com'
recipient = 'recipient_id@yahoo.com'
subject = 'report'
body = "Dear Student, \n Please send your report\n 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 = "\r\n".join(headers)
send_error(sender, recipient, headers, body)

Answer Source

Also have a look at the email package. There are some classes that can simplify the definition of E-Mail messages for you (with examples).

For example you could try (untested):

import smtplib
from email.mime.text import MIMEText

# define content
recipients = ["recipient_id@yahoo.com"]
sender = "sender_id@gmail.com"
subject = "report reminder"
body = """
Dear Student,
Please send your report
Thank you for your attention

# make up message
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ", ".join(recipients)

# sending
session = smtplib.SMTP('smtp.gmail.com', 587)
session.login(sender, 'my password')
send_it = session.sendmail(sender, recipients, msg.as_string())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download