perl 为什么Email::Stuffer base64-encode不同于MIME::Base64,utf 8如何适应?

6ojccjat  于 2023-10-24  发布在  Perl
关注(0)|答案(1)|浏览(188)

我想用Email::Stuffer发送一封简单的电子邮件。正如预期的那样,它将带有非Asynchronous字符的标题编码为编码的单词。但是当我解码它们时(无论是在我的邮件客户端还是在Perl中),我得到了不同的文本,MIME::Base64以不同的方式编码相同的文本。

use strict;
use warnings;
use Email::Stuffer;
use MIME::Base64;

my $text = 'Ümläut';
print "$text in base64: ", encode_base64($text, ''), "\n";
print "and back: ", decode_base64(encode_base64($text)), "\n";

my $stuffer = Email::Stuffer->subject($text);
my $dump = $stuffer->as_string();
print "Mail dump:\n---\n$dump\n---\n";

$dump =~ m{^Subject:\s*=\?UTF-8\?B\?(.+)\?=}m;
my $encoded = $1;
print "in Subject: $encoded\n";
my $decoded = decode_base64($encoded);
print "subject decoded: $decoded\n";

这将打印:

Ümläut in base64: w5xtbMOkdXQ=
and back: Ümläut
Mail dump:
---
Date: Sat, 7 Oct 2023 16:31:59 -0500
MIME-Version: 1.0
Subject: =?UTF-8?B?w4PCnG1sw4PCpHV0?=

---
in Subject: w4PCnG1sw4PCpHV0
subject decoded: Ãmläut

( shell 上的echo "Ümläut" | base64MIME::Base64一致,并且还打印w5 xtbMOkdXQK)
程序源代码在utf8中。当我在use warnings;之后添加use utf8;时,第一个print s不会打印预期的变音符号,但Email::Stuffer可以按预期工作。

�ml�ut in base64: 3G1s5HV0
and back: �ml�ut
Mail dump:
---
Date: Sat, 7 Oct 2023 16:32:50 -0500
MIME-Version: 1.0
Subject: =?UTF-8?B?w5xtbMOkdXQ=?=

---
in Subject: w5xtbMOkdXQ=
subject decoded: Ümläut

这里有什么区别/为什么会发生这种情况,我如何让MIME::Base64Email::Stuffer都同意?

ej83mcc0

ej83mcc01#

->subject需要文本(解码文本,Unicode代码点字符串)。
encode_base64需要字节(例如使用UTF-8编码的文本)。
固定:

use strict;
use warnings;
use feature qw( say );

use utf8;                               # Source code is encoded using UTF-8.
use open ':std', ':encoding(UTF-8)';    # Terminal expects/provides UTF-8.

use Email::Stuffer qw( );
use Encode         qw( decode encode );
use MIME::Base64   qw( decode_base64 encode_base64 );

my $text_ucp = 'Ümläut';                # String of Unicode Code Points.
say $text_ucp;                          # Ümläut

my $text_utf8_base64 = encode_base64( encode( "UTF-8", $text_ucp ), '');
say $text_utf8_base64;                  # w5xtbMOkdXQ=

my $roundtrip_ucp = decode( "UTF-8", decode_base64( $text_utf8_base64 ) );
say $roundtrip_ucp;                     # Ümläut

my $stuffer = Email::Stuffer->subject( $text_ucp );
print $stuffer->as_string();            # =?UTF-8?B?w5xtbMOkdXQ=?=

相关问题