使用perl解码MIME中的附件时出错

时间:2013-07-16 20:46:49

标签: perl mime

我在perl中编写了一个脚本,以便在此处附加图像的多部分MIME消息是脚本

use MIME::Parser;
use FileHandle;

$ffh = FileHandle->new;
if ( $ffh->open(">m2.txt") ) {

    #print <$fh>;
}

### Create an entity:
$top = MIME::Entity->build(
    From    => 'me@myhost.com',
    To      => 'you@yourhost.com',
    Subject => "Hello, nurse!",
    Data    => "How are you today"
);

### Attach stuff to it:
$top->attach(
    Path     => "im.jpg",
    Type     => "image/jpg",
    Encoding => "base64"
);

### Output it:
$top->print($ffh);

之后,我尝试使用以下代码解析上述脚本中生成的输出消息

use MIME::Parser;
use FileHandle;

$fh = FileHandle->new;
if ( $fh->open("<m2.txt") ) {

    #print <$fh>;
}

### Create parser, and set some parsing options:
my $parser = new MIME::Parser;
$parser->output_to_core(1);

### Parse input:
$entity = $parser->parse($fh) or die "parse failed\n";

print $entity->head->get('subject');
print $entity->head->get('from');

print $entity->head->get('to');
print $entity->head->get('cc');
print $entity->head->get('date');
print $entity->head->get('content-type');

my $parts = $entity->parts(1);
my $body  = $parts->bodyhandle;
print $parts->head->get('content-type');

$ffh = FileHandle->new;
if ( $ffh->open(">C:/Users/Aamer/Desktop/im.jpg") ) {
    $body->print($ffh);
}

现在每件事都正确解析并返回正确的值除了输出图像作为附件图像一些如何被破坏我试图十六进制比较它们提取的图像和原始图像之间有一些区别可以任何人告诉我什么是错的这里 ?感谢

2 个答案:

答案 0 :(得分:2)

您的路径名表示您在Windows上,默认情况下Perl以文本模式打开文件。这意味着在写入文件时,它会将图像中每次出现的0x0A(LF)转换为0x0D 0x0A(CRLF),从而破坏您的图像。

以二进制模式打开文件:

$ffh->open("C:/Users/Aamer/Desktop/im.jpg", "wb")

答案 1 :(得分:0)

在附加文件之前是否关闭了文件句柄?可能是一个缓冲问题。关闭文件句柄会将数据刷新到文件中。