我正在尝试使用Ruby mail gem解析电子邮件字符串,而且我正在使用角色编码进行恶魔。请收到以下电子邮件:
MIME-Version: 1.0
Sender: foobar@example.com
Received: by 10.142.239.17 with HTTP; Thu, 14 Jun 2012 06:00:18 -0700 (PDT)
Date: Thu, 14 Jun 2012 09:00:18 -0400
Delivered-To: foobar@gmail.com
X-Google-Sender-Auth: MxfFrMybNjBoBt4O4GwAn9cMsko
Message-ID: <CAGErOzF3FV5NvzN3zUpLGPok96SFzK18Z4HerzyYNALnzgMVaA@mail.gmail.com>
Subject: Re: [Lorem Ipsum] Foo updated the forum topic 'Reply by email test'
From: Foo Bar <foo@example.com>
To: Foo <c49964d167e08e7d4a1930e6565f23c258be19a0@foo.example.com>
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
This email has accents:=A0R=E9sum=E9
>
> --------- Reply Above This Line ------------
>
> Email parsing with accents: R=E9sum=E9
>
> Click here to view this post in your browser
正确编码时,电子邮件正文应为:
This reply has accents: Résumé
>
> --------- Reply Above This Line ------------
>
> Email parsing with accents: Résumé
>
> Click here to view this post in your browser
然而,我有一段时间的魔鬼实际上得到了重音标记。这是我尝试过的:
message = Mail.new(email_string)
body = message.body.decoded
这给了我一个像这样开头的字符串:
This reply has accents:\xA0R\xE9sum\xE9\r\n>\r\n> --------- Reply Above This Line ------------
最后,我试试这个:
body.encoding # => <Encoding:ASCII-8BIT>
body.encode("UTF-8") # => Encoding::UndefinedConversionError: "\xA0" from ASCII-8BIT to UTF-8
有没有人对如何处理此事有任何建议?我很确定它与电子邮件中的“charset = ISO-8859-1”设置有关,但我不确定如何使用它,或者是否有办法使用邮件gem轻松提取它。
答案 0 :(得分:18)
玩了一会后,我发现了这个:
body.decoded.force_encoding("ISO-8859-1").encode("UTF-8") # => "This reply has accents: Résumé..."
message.parts.map { |part| part.decoded.force_encoding("ISO-8859-1").encode(part.charset) } # multi-part
您可以像这样从邮件中提取字符集。
message.charset #=> for simple, non-multipart
message.parts.map { |part| part.charset } #=> for multipart, each part can have its own charset
小心非多部分,因为以下可能会导致麻烦:
body.charset #=> returns "US-ASCII" which is WRONG!
body.force_encoding(body.charset).encode("UTF-8") #=> Conversion error...
body.force_encoding(message.charset).encode("UTF-8") #=> Correct conversion :)
答案 1 :(得分:0)
这对我没有用,所以我想我会坚持我遇到的解决方案以防万一...
基本上必须添加编码默认值并将输出调整为合理的字符串。 https://stackoverflow.com/a/26604049/2386548