Rails ActionMailer adds carriage return (=0D) to end of every line in html

Viewed 1492

My ActionMailer adds a carrige return to the end of every line:

<!DOCTYPE html>=0D
<html>=0D
<head>=0D
...
this is stuff=0D
=0D
This intro has some content in it.=0D
=0D
blah.=0D
=0D

My mail is rendered perfectly fine in the preview host/rails/mailers/user_mailer/periodic_digest.html (and also in mailcatcher), but when I send the mail through Mailgun I end up getting double line spacing between my text.

In app/mailers/user_mailer.rb:periodic_digest

m = mail(from: 'blah', to: 'me')
puts m.html_part.body.decoded

I do get correctly formatted html.

How can I send out my html without the carriage return character =0D being appended to every line?

4 Answers

This isn't an error on Rails' part. Mailgun just handles it in an undesirable manner.

Carriage returns are used to forcibly wrap lines in quoted printable encoded text. If you're sending multipart or plaintext email, RFC 5322 (and 2822 and 822 before it) specify that you must wrap lines at no more than 998 characters. For practical purposes, most email clients wrap closer to 70 characters.

In order to insert a visible newline, you need to use a carriage return followed by a linefeed, which you're probably accustomed to seeing represented as \r\n. This is in contrast to the typical unix-style line endings (just a linefeed) you would have in your code or text files.

<%=  (@mails.html_part.body.decoded.to_s.split).join(" ").html_safe %>

In my case failed test case for these lines:

<td class="quantity">1</td>
<td>Programming Ruby 1.9</td>

on:

assert_match /<td[^>]*>1<\/td>\s*<td>Programming Ruby 1.9<\/td>/, mail.body.encoded

So the fail place was between those lines as \s was not handling new line what puts showed like:

<td class=3D"quantity">1</td>=0D
<td>Programming Ruby 1.9</td>=0D

So the solution was to use:

mail.html_part.body.decoded.to_s

I hope this will help to someone.

I was able to avoid the '= 0D' at the end of each line by removing special characters such as 'ñ' and accents in the text of my email.

Related