您有一些表格格式的数据,因此您可以将其转换为 HTML 表格,该表格将以电子邮件客户端使用的任何字体正确呈现。对于不支持 HTML 的电子邮件客户端,请提供纯文本版本,该版本将以固定宽度的字体呈现。
下面的代码会解析以管道分隔的 CSV 文件,并使用它来构建 HTML 表格和纯文本替代方案。然后将两者都添加到MIME::Entity 对象中,该对象将创建您需要能够正确发送它的所有标头。
我使用过 Text::CSV 和 MIME::Entity,但也有其他 Perl 模块可以完成它们的工作。
use strict;
use MIME::Entity;
use Text::CSV;
my $file="test_input.txt"; # Change this to where your file is
my $subject="An email";
my $from="someone\@somewhere.com";
my $to="someone\@somewhere.com";
# Create the CSV parser. Confusingly the "allow_whitespace" strips whitespace rather than allowing it to pad out fields
my $csv=Text::CSV->new({sep_char => "|", allow_whitespace => 1});
# Build the MIME::Entity object
my $mime_email=MIME::Entity->build(
From => $from,
To => $to,
Subject => $subject,
Type => "multipart/alternative");
my $html="<table>\n";
my $text;
if(open(my $fh,"<",$file)) # Use the modern way of opening a file
{
while(my $line = <$fh>)
{
$text .= $line;
$csv->parse($line);
$html .= "<tr>";
foreach my $field ($csv->fields())
{
$html .= "<td>".$field."</td>";
}
$html .= "</tr>\n";
}
close($fh);
}
$html .= "</table>\n";
$mime_email->attach(Type => "text/plain",Data => $text);
$mime_email->attach(Type => "text/html",Data => $html);
# Send the email
if(open(my $mail,"|-","/usr/sbin/sendmail -t"))
{
$mime_email->print($mail);
close($mail);
}
这将生成一封电子邮件,看起来应该可以在各种电子邮件客户端上以他们喜欢的字体很好地呈现表格。
Content-Type: multipart/alternative; boundary="----------=_1529920158-30125-0"
Content-Transfer-Encoding: binary
MIME-Version: 1.0
X-Mailer: MIME-tools 5.505 (Entity 5.505)
From: someone@somewhere.com
To: someone@somewhere.com
Subject: An email
This is a multi-part message in MIME format...
------------=_1529920158-30125-0
Content-Type: text/plain
Content-Disposition: inline
Content-Transfer-Encoding: binary
hello | morning | 30 | 40 |
Yes | evening | 30 | 50 |
------------=_1529920158-30125-0
Content-Type: text/html
Content-Disposition: inline
Content-Transfer-Encoding: binary
<table>
<tr><td>hello</td><td>morning</td><td>30</td><td>40</td><td></td></tr>
<tr><td>Yes</td><td>evening</td><td>30</td><td>50</td><td></td></tr>
</table>
------------=_1529920158-30125-0--