#!/usr/bin/perl -w
use Mail::POP3Client;
use MIME::Parser;
use MIME::Head;
use strict;
my $pop=new Mail::POP3Client( USER=>"xxxx",
PASSWORD=>"xxxx",
HOST=>"mail.example.com");
my $msgcount=$pop->Count();
my $msgnum;
for $msgnum (1 .. $msgcount){
print "message number: $msgnum\n";
# get headers
my $header=$pop->Head($msgnum);
# get body
my $body=$pop->Body($msgnum);
# get whole message
my $message=$pop->HeadAndBody($msgnum);
my $parser=new MIME::Parser;
# disable output to file/dir
$parser->output_to_core(1);
my $entity = $parser->parse_data($message);
# get the number of parts of the message (if multipart)
my $num_parts = $entity->parts;
my @parts = $entity->parts;
my $bodydata;
if ($num_parts > 0) {
# more than one part, mime-ahoy?
my $part;
for $part(@parts){
# get mime type
my $type=$part->mime_type;
my $bhandle=$part->bodyhandle;
# special treatment for text and html
if (($type =~ /text/i) || ($type=~ /html/i)){
if (my $io = $part->open("r")) {
while (defined($_ = $io->getline)) {
$bodydata .= $_;
}
$io->close;
}
print $bodydata,"\n";
} else {
# must be an attachment of sorts or
# at least not text/html
my $content .= $bhandle->as_string if defined $bhandle;
# method 1
# my $file_name = $entity->head->recommended_filename ||
# $entity->bodyhandle->path;
# method 2
#my $mimehead=MIME::Head->new;
#my $file_name=$mimehead->recommended_filename;
# method 3
#my $file_name = $bhandle->{MB_Path};
print "path: $file_name\n";
# dump attachment to outfile
# (works when name is specified)
open(OUT,"> /path/to/attachments/$file_name");
# is this needed?
local $/ = undef;
print OUT $content,"\n";
close(OUT);
}
}
} else {
# plaintext or html!
if (my $io = $entity->open("r")) {
while (defined($_ = $io->getline)) {
$bodydata .= $_;
}
$io->close;
}
print $bodydata,"\n";
}
$entity->purge;
}
exit;
----------------------------
#!/usr/bin/perl
use File::Basename;
use MIME::Parser;
my $parser = MIME::Parser->new;
#ファイルの一時保存場所を指定
$parser->output_dir('/tmp');
#標準入力からメールを取得
my $entity = $parser->parse(*STDIN);
#FromとSubjectのみ取り出し
#$entity->head;
#my $from = $header->get('From');
#my $subject = $header->get('Subject');
#添付ファイルがある場合のみ処理
if($entity->is_multipart){
#パートの数(本文と添付ファイルの合計数)
$count = $entity->parts;
#メール本文以外(添付のみ)を取り出し(本文は0番目のため、一番目から取り出し)
for($i = 1; $i < $count; $i++){
#ファイル名を含むパスを取り出し
$path = $entity->parts($i)->bodyhandle->path;
#ファイル名を取り出し
$filename = (fileparse($path))[0];
#添付ファイルを書き出し
open(FILE, "> /var/spool/mail/mail/$filename");
print FILE $entity->parts($i)->bodyhandle->as_string;
close(FILE);
}
}
阅读(709) | 评论(0) | 转发(0) |