2013年11月17日 星期日

使用Perl forward echange mail

#!/usr/bin/perl

#use strict;
#use warnings;
#use Authen::NTLM;
use Mail::IMAPClient;
use Mail::IMAPClient::BodyStructure;
use MIME::Parser::Filer;
use Encode;
use Mail::Sendmail;

my $username = "xxx";
my $password = "yyy";
my $file = "message.idx";
my $msg;
my $nextMsg;

## Settings for connecting to IMAP server
my $imap = Mail::IMAPClient->new(
    Server            => 'mail1.bigsun-energy.com',
    User              => $username,
    Password          => $password,
    Port              => 143,
    Debug => 1
) or die "Cannot connect through IMAPClient: $@\n";

$imap->select("INBOX");
my @messages = $imap->messages;
my $filer    = MIME::Parser::FileInto->new();
print "There are " . scalar @messages . " messages waiting.\n";

open IN,$file;
while (my $line = <IN>) {
   $msg = $line;
}
close IN;

for (my $i=0 ; $i<=$#messages ; $i++) {
   if ($messages[$i] > $msg) {
      print "Processing $messages[$i]...\n";
      $nextMsg = $messages[$i];
     
      my $hashRef = $imap->parse_headers($messages[$i],"ALL");
      my $aryRef = $hashRef->{"Content-Type"};
      my $contentTypes = join ",",@$aryRef;
     
      my ($contentType) = $contentTypes =~ m/^(.*);/;
      my ($boundary) = $contentTypes =~ m/"(.*)"/;
     
      my $ref = $hashRef->{From};
      my $from = join ",",@$ref;
      #$from =~ s/<|>//g;
     
      my $msg_subject = Encode::decode( 'MIME-Header', $imap->subject($messages[$i]) );
      my $msg_body = $imap->body_string($messages[$i]);
      my @lines = split /\n/,$msg_body;
      pop @lines;pop @lines;
      $msg_body = join "\n",@lines;     
     
      my %mail = ( To      => 'zzz@www',
                   From    => 'aaa@bbb',
                   Subject => "Fwd : ".$msg_subject." [From : $from]"
                 );
      $mail{smtp} = "mail1.ccc";
      $mail{'content-type'} = "$contentType; boundary=\"$boundary\"";  

      $mail{body} = <<END_OF_1;
$msg_body
END_OF_1
      sendmail(%mail) if not $from =~ /sysadmin/;
      #print "$mail{body}";
      #print "\n############################\n$contentType; boundary=\"$boundary\"\n";
      #print "\n############################\n$mail{body}\n";
      $i = $#messages;
   }
}

$imap->close();

open OUT,">$file";
print OUT $nextMsg;
print "#############\n$nextMsg\n";
close OUT;

沒有留言:

張貼留言