开发者

In ruby on rails, how do you decode a content-transfer-encoding base64 Mail object

I am working on ruby on rails ActionMailer. What I have done is that I had a background process polling my gmail account and I retrieve mails with 'RFC822' protocol. I then send these mails to a receive method inside my ActionMailer class.

While I can successfully process almost all of the incoming mails, sometimes I do encounter international mails, which开发者_Python百科 have accent marks in english characters. When displaying the bodies of these mails to STDOUT, they appear to be some random characters as follow because I think the decoding is wrong...

This is the body of the mail object when I print it on the screen:

"PGh0bWw+PGhlYWQ+PG1ldGEgaHR0cC1lcXVpdj0iQ29udGVudC1MYW5ndWFnZSIgY29udGVudD0i
ZW4tdXMiPjxtZXRhIGh0dHAtZXF1aXY9IkNvbnRlbnQtVHlwZSIgY29udGVudD0idGV4dC9odG1s
OyBjaGFyc2V0PVVURi04Ij48bWV0YSBuYW1lPSJHRU5FUkFUT1IiIGNvbnRlbnQ9Ik1pY3Jvc29m
dCBGcm9udFBhZ2UgNC4wIj48bWV0YSBuYW1lPSJQcm9nSWQiIGNvbnRlbnQ9IkZyb250UGFnZS5F
ZGl0b3IuRG9jdW1lbnQiPjx0aXRsZT5OZXcgUGFnZSAxPC90aXRsZT48L2hlYWQ+PGJvZHk+PHRh
YmxlPjx0cj48dGQ+PHA+PGZvbnQgZmFjZT0iQXJpYWwiIGNvbG9yPSJibGFjayIgc2l6ZT0iMSI+
PGI+Q29udGV1ZG8gZW52aWFkbyBkbyBtZXUgQ2VsdWxhciBWaXZvPC9iPjwvZm9udD48L3A+PC90
ZD48L3RyPjx0YWJsZSBib3JkZXI9MD48dHI+PHRkIGNvbHNwYW49MT48aHIgY29sb3I9IjgxODFE
QiI+PC90ZD48L3RyPjx0cj4KPHRyPjx0ZCBjb2xzcGFuPTEgYWxpZ249IkNlbnRlciI+PGZvbnQg
ZmFjZT0iQXJpYWwiIGNvbG9yPSJibGFjayIgc2l6ZT0iMyI+I3IgZm9jbyBkZSBkZW5ndWUgI24g
YnJhc2lsICNzIHNwICNjIHPDo28gcGF1bG8gI2EgcnVhIG1hcmFuaMOjbyBjb20gcnVhIGFyYWNh
anU8L2ZvbnQ+PC90ZD48L3RyPgo8L3RyPjx0cj4KPHRkIGNvbHNwYW49MT4KPGhyIGNvbG9yPSI4
MTgxREIiPgo8L3RkPgo8L3RyPgo8L3RhYmxlPgo8L3RhYmxlPgo8L2JvZHk+CjwvaHRtbD4="

These international mails have Content-Transfer-Encoding:base64 as opposed to 7bit. So what do I need to do so that I can correctly decode the email? I have tried things like Base64.decode64, but it complains that there is no unpack method defined.

I have been working on this for couple hours with no luck. Could anyone please help me?

Thank you


At least nowadays ActionMailer is able to correctly decode those emails. This should work:

message = Mail.new(encoded_body)
message.html_part.body.decoded


It looks like the parameter you provide to Base64.decode is not a string. (Because decode falls back to String.unpack)

From ruby-doc:

def decode64(str)
  str.unpack("m").first
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜