9

我正在尝试使用Ruby 邮件 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 轻松提取它。

4

2 回答 2

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 :)
于 2012-06-14T18:54:31.593 回答
0

这对我不起作用,所以我想我会坚持我得到的解决方案,以防它帮助任何人......

基本上必须添加编码默认值并将输出调整为合理的字符串。 https://stackoverflow.com/a/26604049/2386548

于 2014-10-28T08:36:48.093 回答