Last active
October 22, 2016 13:26
-
-
Save pstray/8f0e9062792a0ea50d05 to your computer and use it in GitHub Desktop.
Function to encode mail headers that aren't just plain ascii, like subject. use as encode_header('UTF-8', 'q', $subject);
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sub encode_header { | |
my $charset = lc $_[0]; | |
my $encoding = lc $_[1]; | |
my $text = $_[2]; | |
my @ret; | |
my $pre = "=?$charset?$encoding?"; | |
my $suf = "?="; | |
my $max = 75 - length($pre) - length($suf); | |
if ($encoding eq 'q') { | |
my $q; | |
for my $char (split //, $text) { | |
my $data = encode($charset, $char); | |
for ($data) { | |
s{([^ !*+/0-9A-Za-z-])}{sprintf("=%02X", ord($1))}ge; | |
s/ /_/g; | |
} | |
if (length($q)+length($data) > $max) { | |
push @ret, "$pre$q$suf"; | |
$q = "$data"; | |
} | |
else { | |
$q .= $data; | |
} | |
} | |
if (length $q) { | |
push @ret, "$pre$q$suf"; | |
} | |
} | |
elsif ($encoding eq 'b') { | |
my $m = int($max*3/4); | |
my $d; | |
for my $char (split //, $text) { | |
my $data = encode($charset, $char); | |
if (length($d)+length($data) > $m) { | |
push @ret, $pre.encode_base64($d).$suf; | |
$d = $data; | |
} | |
else { | |
$d .= $data; | |
} | |
} | |
if (length($d)) { | |
push @ret, $pre.encode_base64($d).$suf; | |
} | |
} | |
return join "\r\n\t", @ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment