Son of a Beach
Son of a Beach

Reputation: 1779

Python email loses newline on first line only

My Python script takes a list of lists and creates the text of an email body by joining the inner lists' elements with a "," and appends each of these with a newline like so:

for row in rows:
    emailBody += ",".join(row) + "\n"

(I know that I can do something similar using the CSV module, but I'm aiming to do without it - at least for now.)

Then later it sends the email by using:

import smtplib
from email.mime.text import MIMEText

smtpServer = serverDNS
msg = MIMEText(emailBody, "plain")
msg['from'] = fromAddress
msg['to'] = ", ".join(recipients)
msg['subject'] = subject
smtp = smtplib.SMTP(smtpServer)
smtp.sendmail(msg['from'], recipients, msg.as_string())
smtp.quit()

This works fine, except that the newline on the first line gets ignored and the first two lines end up on one line. The newline on every other line is just fine.

If I manually add an extra newline to the last item of the first line, then the email has TWO newlines after the first line, so that there is a blank line between the first two lines.

What is going on here? How can I get this to behave as expected?

Note that the first line (the first list) consists of a bunch of hard-coded strings. So it's a very simple list. All the other lines are dynamically generated, but are all simple string values in the end (otherwise the 'join' would complain, right?).

If I simply print emailBody, it prints fine. It is only when converting it to an email that the first line's newline gets lost.

I've also tried using "\r\n" instead of just "\n". Same result.

Upvotes: 2

Views: 2441

Answers (1)

Son of a Beach
Son of a Beach

Reputation: 1779

This appears to be an OUTLOOK "Feature" (I'd call it a bug!), not a problem with my Python code. Unfortunately, I'm stuck with Outlook at work. But I found that if I send the email to both the work address and my private address, it shows up perfectly fine on my private email, but wrong in my work email!

Then I noticed that in Outlook, there is a line of small grey text near the top of the email that says "Extra line breaks in this message were removed." Clicking on this line restores the line breaks and the email is then displayed correctly!

Any idea why Outlook does this? Any idea why it does this on some lines and not others, and how I can code my Python to send emails that wont make Outlook "fix" them?

Outlook Fix:

Unfortunately, I can't do this for all the people that may receive these emails. However, I did find a preference in Outlook for "Remove extra line breaks in plain text messages" which was on, so I've turned it off, and this has resolved the problem in my Outlook client, at least.

I will have to communicate this to all other recipients of these emails if I cannot figure out how to format them so that Outlook doesn't try to "Fix" them.

Upvotes: 2

Related Questions