问题
I am using Sendgrid to send email to a mailing list, using the X-SMTPAPI header to specify the multiple recipients. From the Sendgrid documentation "Headers must be wrapped to keep the line length under 72."
I am using the ActionMailer to send emails, and setting the X-SMTPAPI header using the headers
method. To keep lines less than 72 characters, I have tried replacing each comma with a comma+newline+space. For example,
headers["X-SMTPAPI"] = {
:to => ['user1@example.com','user2@example.com','user3@example.com','user4@example.com','user5@example.com','user6@example.com']
}.to_json.gsub(',',",\n ")
Instead of getting newlines in my header, I am getting the following (from the log file)
X-SMTPAPI: {"to":["user1@example.com",=0A "user2@example.com",=0A "user3@example.com",=0A "user4@example.com",=0A "user5@example.com",=0A "user6@example.com"]}
Note that the \n characters are being replaced with =0A
. This sequence is rejected as invalid by the Sendgrid server.
Any ideas what I can do to get the proper newlines into the header?
Edit: I tried adding a "puts headers" to see what is being set in the headers. Then is what I found
Date: Sat, 13 Apr 2013 18:21:36 -0400
Message-ID: <5169da701cd26_5343fe1776afc50749b4@saunders.mail>
Mime-Version: 1.0
Content-Type: text/plain
Content-Transfer-Encoding: 7bit
X-SMTPAPI: {"to":["user1@example.com",=0A "user2@example.com",=0A
"user3@example.com",=0A "user4@example.com",=0A "user5@example.com",=0A
"user6@example.com"]}
Note the newlines I am adding are still showing up as "=0A". But something appears to be adding wrapping on its own. Is this wrapping automatic, and sufficient to keep my header line length from exceeding the requirements?
回答1:
ActionMailer actually will handle folding and encoding the lines for you if you give it the proper spacing to do so. You should use JSON.generate
to give it the spacing:
Ex.
headers["X-SMTPAPI"] = JSON.generate({
:category => "welcome_email",
:to => ['user1@example.com','user2@example.com','user3@example.com','user4@example.com','user5@example.com','user6@example.com']
}, :indent => ' ')
Which would result in:
X-SMTPAPI: { "category":"welcome_email", "to":[ "user1@example.com",
"user2@example.com", "user3@example.com", "user4@example.com",
"user5@example.com", "user6@example.com"]}
As you can see, when ActionMailer encounters whitespace, it will wrap things for you - no need for the usual \r\n
.
回答2:
It seems like characters in headers have to be encoded according to the rules of RFC 2047 [14].
Accodingly to ASCII table %0A
states for \n
来源:https://stackoverflow.com/questions/15992281/newlines-resolved-as-0a-in-sendgrid-x-smtpapi-header