【问题标题】:Error in decoding attachment in MIME using perl使用 perl 在 MIME 中解码附件时出错
【发布时间】:2013-07-15 05:32:13
【问题描述】:

我在 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);
}

现在每件事都正确解析并返回正确的值,除了输出图像作为附件图像有些损坏我试图用十六进制比较它们提取的图像和原始图像之间存在一些差异谁能告诉我出了什么问题这里 ?谢谢

【问题讨论】:

    标签: perl mime


    【解决方案1】:

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

    以二进制模式打开文件:

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

    【讨论】:

    • 非常感谢,问题和你说的一模一样,虽然“wb”在windows上对我不起作用。 binmode($ffh) 确实为我工作。只是为了将来的帮助分享这个,但真的很感谢
    • "wb" 应该可以工作。添加"wb" 时,您是否删除了文件名前面的&gt;
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2013-04-28
      • 2015-09-24
      • 2011-02-17
      • 1970-01-01
      • 2013-12-10
      • 2012-05-21
      • 1970-01-01
      • 2016-01-04
      • 2014-11-27
      相关资源
      最近更新 更多