Email subject MIME encoding in Perl.

梦想与她 提交于 2019-12-31 04:05:07

问题


I am trying to send an email with non-ASCII characters in the subject line under Perl 5.8.5. My simple example uses the word "Änderungen" (German umlaut), but instead of correctly converting the "Ä" the subject line will always turn out as "Ã?nderungen".

#!/usr/bin/env perl

use warnings;
use strict;
use Encode qw(decode encode);

my $subject = "Änderungen";
my $subject_encoded = encode("MIME-Q", $subject);

[...]

open(MAIL, "| /usr/sbin/sendmail -n -t $recipient") || return "ERROR";
print MAIL 'Content-Type: text/plain; charset="utf-8"\n';
print MAIL "To: $recipient\n";
print MAIL "From: $from\n";
print MAIL "Reply-To: $from\n";
print MAIL "Subject: $subject\n\n";
print MAIL "$body\n\n";
print MAIL ".\n";
close(MAIL);

The content of $subject_encoded prints as =?UTF-8?Q?=C3=83=C2=84nderungen?= while an online encoder tool shows that it actually should be =?UTF-8?Q?=C3=84nderungen?=.

When manually constructing the subject string with the latter encoding the mail subject will correctly display "Änderungen" in my e-mail software so the problem seems to be with the actual Perl encode command. I am trying to utilize the quoted-printable encoding, but encoding via MIME-B and MIME-Header will also lead to the wrong representation of "Ã?nderungen".

I did check the file format of my codefile and the charset is also returned as utf-8. Therefore I am at a loss why Perl is apparently encoding it the wrong way. Any ideas or something I might have overlooked ?


回答1:


Your editor treats the file as UTF-8, so it shows

my $subject = "Änderungen";

Perl effectively treats the file as iso-8859-1, so it sees

my $subject = "Ã?nderungen";

Tell Perl you encoded your script using UTF-8 by adding

use utf8;



回答2:


In your question, you declared:

my $subject_encoded = encode("MIME-Q", $subject);

But you didn't use it later.

print MAIL "Subject: $subject\n\n";

should be:

print MAIL "Subject: $subject_encoded\n\n";


来源:https://stackoverflow.com/questions/22989202/email-subject-mime-encoding-in-perl

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