当前位置:软件学习 > 其它软件 >>

perl处理imap数据

最近开始用imap来处理邮件,写了些小脚本来帮助整理文件夹。这是其中的一个小片段,非常凌乱。
 
 #!/usr/bin/perl
 
 use strict;
use warnings;
use Encode;
use Encode::IMAPUTF7;
use threads;
#use threads::shared;
use Thread::Queue;
use Mail::IMAPClient;
 
my $host = 'imap.aliyun.com';
my $user = 'yunshu@aliyun.com';
my $pwd = 'icy';
my $max_thread = 5;
 
my $imap = Mail::IMAPClient->new( Server   => $host,
        User     => $user,
        Password => $pwd,
) or die "Cannot connect: $@";
 
#print "Connect to imap server successful.\n";
 
=pod my @folders = $imap->folders; foreach ( @folders ) {         print encode('gbk', decode('imap-utf-7', $_)), "\n"; } =cut
#$imap->select( encode('imap-utf-7', decode('gbk','安全监控')) );
 
# get all mail in INBOX
$imap->select( 'INBOX' );
my @results = $imap->search('UNDELETED') or warn "get nothing\n";
$imap->close;
$imap->disconnect;
 
print scalar @results," mails in inbox\n";
my $queue = Thread::Queue->new();
foreach( @results )
{
        $queue->enqueue( $_ );
}
print $queue->pending()." mails in queue.\n";
 
for( 1 ... $max_thread )
{
        $queue->enqueue( undef );
}
 
sleep 1;
my @thrs = [ ];
for( 1 ... $max_thread )
{
        $thrs[$_] = threads->create( \&MoveMail );
}
 
sleep 1;
print "create threads finished.\n";
 
for( 1 ... $max_thread )
{
        $thrs[$_]->join();
}
print "all done.\n";
 
sub MoveMail
{
        my $imap = Mail::IMAPClient->new( Server   => $host,
                User     => $user,
                Password => $pwd,
        );
 
        if( !defined $imap )
        {
                warn "Cannot connect: $@";
                return;
        }
                print "thread ".threads->self()->tid()." connect to imap server successful.\n";
        $imap->select( 'INBOX' );
                print "thread ".threads->self()->tid()." select inbox successful.\n";
 
        while (my $msg = $queue->dequeue())
        {
                eval
                {
                                $| = 1;
                                #print "thread ".threads->self()->tid()." process $msg.\n";
                                my $from = $imap->get_header($msg, 'From');
 
                      if( defined($from) )
                      {
                        if( $from =~ /monitor/ )
                                {
                                $imap->move( encode('imap-utf-7', decode('gbk','安全监控')), $msg );
                                print ".";
                                }
                                elsif( $from =~ 'ddos@ops.aliyun-inc.com' )
                                {
                                $imap->move('DDOS', $msg);
                                print "x";
                        }
                      }
                };
        }
        $imap->close;
       $imap->disconnect;
        return;
}
 

作者 云舒
补充:软件开发 , 其他 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,