如何使用Perl将电子邮件保存到文件?

Nat*_*pos 1 email perl

我学习Perl并且我想创建一个简单的应用程序来获取我的所有电子邮件并将它们保存到文件中,但我怎么能这样做?谢谢.

Sin*_*nür 6

我曾经使用以下脚本在切换ISP之前过滤SpamAssassin标记的电子邮件:

#!/usr/bin/perl

use strict;
use warnings;

$| = 1;

use constant SEVERITY => 5;

use Mail::POP3Client;
use Term::ReadKey;

my $user = shift;

my $pop = Mail::POP3Client->new(
    HOST => '127.0.0.1', 
    PORT => 9999
);

my $pass = prompt_password();
print "\n";

$pop->User($user);
$pop->Pass($pass);
$pop->Connect or die $pop->Message;

my $count = $pop->Count;

$count >= 0 or die "Failed to get message count.\n";
$count >  0 or die "No messages in mailbox.\n";

my @to_delete;

print "Scanning messages:  ";

my $to_delete = 0;
for my $msg_num (1 .. $count) {
    my @headers = $pop->Head($msg_num);

    for my $h (@headers) {
        if($h =~ /^X-Spam-Level: (\*+)/) {
            if(SEVERITY <= length $1) {
                $to_delete += 1;
                $pop->Delete($msg_num);
                print "\b*>";
            } else {
                print "\b->";
            }
        }
    }
}

print "\b ... done\n";

use Lingua::EN::Inflect qw( PL );

if( $to_delete ) {
    printf "%d %s will be deleted. Commit: [Y/N]?\n",
        $to_delete, PL('message', $to_delete);
    $pop->Reset unless yes();
}

$pop->Close;

print "OK\n";

sub yes {
    while(my $r = <STDIN>) {
        $r = lc substr $r, 0, 1;
        return 1 if $r eq 'y';
        next unless $r eq 'n';
        last;
    }
    0;
}

sub prompt_password {
    print 'Password: ';
    ReadMode 2;
    my $pass = ReadLine 0;
    ReadMode 0;
    chomp $pass;
    return $pass;
}
Run Code Online (Sandbox Code Playgroud)

改变这一点是微不足道的,这样可以节省信息.请参阅Mail :: POP3Client.