How to encode mail subject in perl?

耗尽温柔 提交于 2019-12-04 08:49:58
matthias krull

Use Encode, it is a core module.

perl -Mutf8 -MEncode -E 'say encode("MIME-Header", "Votre fichier a bien été envoyé")'

… will output either one of:

=?UTF-8?Q?Votre=20fichier=20a=20bien=20?= =?UTF-8?Q?=C3=A9t=C3=A9=20envoy=C3=A9?=
=?UTF-8?B?Vm90cmUgZmljaGllciBhIGJpZW4gw6l0w6kgZW52b3nDqQ==?=

And decode with:

perl -C -MEncode -E 'say decode("MIME-Header", "=?UTF-8?Q?Votre=20fichier=20a=20bien=20?= =?UTF-8?Q?=C3=A9t=C3=A9=20envoy=C3=A9?=")'
perl -C -MEncode -E 'say decode("MIME-Header", "=?UTF-8?B?Vm90cmUgZmljaGllciBhIGJpZW4gw6l0w6kgZW52b3nDqQ==?=")'

Which will print:

Votre fichier a bien été envoyé

If you still have the same results, you should give more information on your Perl environment. The version is a good starter.

Another module that handles MIME encoding of non-ASCII strings is Email::MIME::RFC2047. For example

use strict;
use warnings;
use utf8;

use Email::MIME::RFC2047::Encoder;
use Email::MIME::RFC2047::Decoder;

binmode(STDOUT, ':utf8');

my $encoder = Email::MIME::RFC2047::Encoder->new;
my $encoded = $encoder->encode_text('Votre fichier a bien été envoyé');
print "$encoded\n";

my $decoder = Email::MIME::RFC2047::Decoder->new;
my $decoded = $decoder->decode_text($encoded);
print "$decoded\n";

prints

Votre fichier a bien =?utf-8?Q?=c3=a9t=c3=a9_envoy=c3=a9?=
Votre fichier a bien été envoyé

Some benefits of Email::MIME::RFC2047 over Encode:

  • It tries hard to use MIME encoding for as few words as possible, also by using quoted strings in phrases.
  • It supports correct decoding of MIME phrases used in To, From, or Cc headers (impossible with Encode).
  • It supports other character sets than UTF-8.
  • It encodes space as underscore in MIME-Q encoded words.
  • It has fewer bugs than Encode (none that I know of).

Disclosure: I am the author of the module.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!