How to get line breaks in e-mail sent using Python's smtplib?
Question:
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 n
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 + "rnrn" + body)
session.quit()
return send_it
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = '[email protected]'
recipient = '[email protected]'
subject = 'report'
body = "Dear Student, n Please send your reportn 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 = "rn".join(headers)
send_error(sender, recipient, headers, body)
Answers:
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 n
to the double rn
which is used in email.
Your text would be:
"Dear Student, rn Please send your reportrn Thank you for your attention"
You have your message body declared to have HTML content ("Content-Type: text/html"
). The HTML code for line break is <br>
. You should either change your content type to text/plain
or use the HTML markup for line breaks instead of plain n
as the latter gets ignored when rendering a HTML document.
As a side note, 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 = ["[email protected]"]
sender = "[email protected]"
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.starttls()
session.login(sender, 'my password')
send_it = session.sendmail(sender, recipients, msg.as_string())
session.quit()
Setting the content-type header to Content-Type: text/plain
(with rn
at the end) allowed me to send multi-line plain-text emails.
Outlook will remove line feeds from plain text it believes are extras. https://support.microsoft.com/en-us/kb/287816
You can try below update to make the lines look like bullets. That worked for me.
body = "Dear Student, n- Please send your reportn- Thank you for your attention"
In my case 'rn'
didn’t work, but 'rrn'
did. So my code was:
from email.mime.text import MIMEText
body = 'Dear Student,rrnPlease send your reportrrnThank you for your attention'
msg.attach(MIMEText(body, 'plain'))
The message is written in multiple lines and is displayed correctly in Outlook.
I ran into this issue as well and this thread was helpful in determining why it was happening in the first place. I was at a lost, because I knew my code was correct. I tried a few things, but what worked for me was adding a tn for each line in the body.
from email.mime.text import MIMEText
lines = ['line1', 'line2', 'line3']
body = 'tn'.join(lines)
msg = MIMEText(body)
I’ve also run into this as well. I had found a little bit of white space at the end of the line was enough for my SMTP service to recognize the new line
body = 'value of variable x = ' + myVarX + " rn"
+ 'value of variable y = ' + myVarY
I believe this to be more of a SMTP issue, rather than a Python issue, which may explain the range in solutions in this thread
Adding nn
works for me
body = """"""
body += "This is message1nn"
body += "This is message2"
Output:
This is message1
This is message2
please check the version of python.
for version 3.11.1,
you should use ‘rn’ for line break
reference the official doc https://docs.python.org/3/library/smtplib.html#:~:text=using%20BytesGenerator%20with-,%5Cr%5Cn%20as%20the%20linesep,-%2C%20and%20calls%20sendmail
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 n
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 + "rnrn" + body)
session.quit()
return send_it
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = '[email protected]'
recipient = '[email protected]'
subject = 'report'
body = "Dear Student, n Please send your reportn 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 = "rn".join(headers)
send_error(sender, recipient, headers, body)
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 n
to the double rn
which is used in email.
Your text would be:
"Dear Student, rn Please send your reportrn Thank you for your attention"
You have your message body declared to have HTML content ("Content-Type: text/html"
). The HTML code for line break is <br>
. You should either change your content type to text/plain
or use the HTML markup for line breaks instead of plain n
as the latter gets ignored when rendering a HTML document.
As a side note, 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 = ["[email protected]"]
sender = "[email protected]"
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.starttls()
session.login(sender, 'my password')
send_it = session.sendmail(sender, recipients, msg.as_string())
session.quit()
Setting the content-type header to Content-Type: text/plain
(with rn
at the end) allowed me to send multi-line plain-text emails.
Outlook will remove line feeds from plain text it believes are extras. https://support.microsoft.com/en-us/kb/287816
You can try below update to make the lines look like bullets. That worked for me.
body = "Dear Student, n- Please send your reportn- Thank you for your attention"
In my case 'rn'
didn’t work, but 'rrn'
did. So my code was:
from email.mime.text import MIMEText
body = 'Dear Student,rrnPlease send your reportrrnThank you for your attention'
msg.attach(MIMEText(body, 'plain'))
The message is written in multiple lines and is displayed correctly in Outlook.
I ran into this issue as well and this thread was helpful in determining why it was happening in the first place. I was at a lost, because I knew my code was correct. I tried a few things, but what worked for me was adding a tn for each line in the body.
from email.mime.text import MIMEText
lines = ['line1', 'line2', 'line3']
body = 'tn'.join(lines)
msg = MIMEText(body)
I’ve also run into this as well. I had found a little bit of white space at the end of the line was enough for my SMTP service to recognize the new line
body = 'value of variable x = ' + myVarX + " rn"
+ 'value of variable y = ' + myVarY
I believe this to be more of a SMTP issue, rather than a Python issue, which may explain the range in solutions in this thread
Adding nn
works for me
body = """"""
body += "This is message1nn"
body += "This is message2"
Output:
This is message1
This is message2
please check the version of python.
for version 3.11.1,
you should use ‘rn’ for line break
reference the official doc https://docs.python.org/3/library/smtplib.html#:~:text=using%20BytesGenerator%20with-,%5Cr%5Cn%20as%20the%20linesep,-%2C%20and%20calls%20sendmail