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