如何使用Perl Email :: Mime内嵌图像?

时间:2018-12-03 19:45:41

标签: perl email mime-mail

我正在尝试发送带有嵌入式图像的HTML电子邮件。我将不得不使用本机unix东西和Email::Mime,因为这些是我发现安装在盒子里的唯一东西。我正在创建Email::Mime消息并将其发送到sendmail。我使用cid来插入图像,但是由于某些原因,我一直以附件的形式获取图像。

有人可以帮我吗,代码片段在下面。

sub send_mail(){

use MIME::QuotedPrint;
use HTML::Entities;
use IO::All;
use Email::MIME;

$boundary = "====" . time() . "====";

$text = "HTML mail demo\n\n"
      . "This is the message text\n"
      . "Voilà du texte qui sera encodé\n";

$plain = encode_qp $text;

$html = encode_entities($text);
$html =~ s/\n\n/\n\n<p>/g;
$html =~ s/\n/<br>\n/g;
$html = "<p><strong>" . $html . "</strong></p>";
$html .= '<p><img src="cid:123.png" class = "mail" alt="img-mail" /></p>';

# multipart message
    my @parts = (
        Email::MIME->create(
            attributes => {
                content_type => "text/html",
                encoding     => "quoted-printable",
                charset      => "US-ASCII",
            },
            body_str => "<html> $html </html>",
        ),
        Email::MIME->create(
            attributes => {
                content_type => "image/png",
                name => "pie.png",
                disposition  => "Inline",
                charset      => "US-ASCII",
                encoding     => "base64",
                filename => "pie.png",
                "Content-ID" => "<123.png>",
                path => "/local_vol1_nobackup/user/ramondal/gfxip_gfx10p2_main_tree03/src/verif/ge/tb",
            },
            body => io("pie.png")->binary->all,
        ),
    );

     my $email = Email::MIME->create(
         header_str => [
             To => 'abc@xyz.com',
             Subject => "Test Email",
         ],
         parts      => [@parts],
     );


    # die $email->as_string;

    open(MAIL, "|/usr/sbin/sendmail -t") or die $!;

    print MAIL $email->as_string;

    close (MAIL);

    }

1 个答案:

答案 0 :(得分:4)

您的代码有两个问题。

首先,它应该是Content-Id: <123.png> MIME头,但是您的代码会为content-id=<123.png>头生成一个Content-Type参数。要解决此问题,请不要将Content-Id添加到attributes,而应添加为header_str

...
Email::MIME->create(
    header_str => [
        "Content-ID" => "123.png",
    ],
    attributes => {
        content_type => "image/png",
...

第二,代码为邮件创建multipart/mixed内容类型。但是图像和HTML是相关的,因此它应该是multipart/related内容类型:

...
my $email = Email::MIME->create(
    header_str => [
        To => 'abc@xyz.com',
        Subject => "Test Email",
    ],
    attributes => {
        content_type => 'multipart/related'
    },
    parts      => [@parts],
);
...