みけCATのにっき(仮)
つれづれなるまゝに、日くらし、PCにむかひて、心に移りゆくよしなし事を、そこはかとなく書きつくれば、あやしうこそものぐるほしけれ。
(本当か!?)
出典

Perlでメールを受信

アバター
みけCAT
記事: 6734
登録日時: 14年前
住所: 千葉県
連絡を取る:

Perlでメールを受信

投稿記事 by みけCAT » 13年前

PerlでPOP3を使ってメールを受信するプログラムを書きました。

CODE:

#!/usr/bin/perl

if(@ARGV  \n";
	exit(1);
}

open(OUT,"> log.txt") or die "Can't open log file.\n";

$addr = (gethostbyname($ARGV[0]))[4];
$name = pack("S n a4 x8", 2, 110, $addr);
socket(S, 2, 1, 0);
connect(S, $name);
binmode(S);
select(S); $| = 1; select(stdout);

print ">(connect)\n";
print OUT ">(connect)\n";
$ans="";
while() {
	$ans .= $_;
	print $ans;
	if($ans =~ /\r\n/){last;}
}
print OUT $ans;
if($ans !~ /^\+OK/) {
	print OUT "!connect error\n";
	print "connect error\n";
	&sendquit;
	close(OUT);
	exit(1);
}

print ">USER\n";
print OUT ">USER ****\n";
print S "USER $ARGV[1]\r\n";
$ans="";
while() {
	$ans .= $_;
	if($ans =~ /\r\n/){last;}
}
print OUT $ans;
if($ans !~ /^\+OK/) {
	print OUT "!USER error\n";
	print "USER error\n";
	&sendquit;
	close(OUT);
	exit(1);
}

print ">PASS\n";
print OUT ">PASS ****\n";
print S "PASS $ARGV[2]\r\n";
$ans="";
while() {
	$ans .= $_;
	if($ans =~ /\r\n/){last;}
}
print OUT $ans;
if($ans !~ /^\+OK/) {
	print OUT "!PASS error\n";
	print "PASS error\n";
	&sendquit;
	close(OUT);
	exit(1);
}

print ">LIST\n";
print OUT ">LIST\n";
print S "LIST\r\n";
$ans="";
while() {
	$ans .= $_;
	if($ans =~ /\r\n/){last;}
}
print OUT $ans;
if($ans !~ /^\+OK/) {
	print OUT "!LIST error\n";
	print "LIST error\n";
	&sendquit;
	close(OUT);
	exit(1);
}

$ans="";
while() {
	$ans .= $_;
	if($ans =~ /\.\r\n/){last;}
}
$ans =~ s/\.\r\n//;
if(open(LISTFILE,"> list.txt")) {
	print LISTFILE $ans;
	close(LISTFILE);
}

@lists=split(/\r\n/,$ans);
for($i=0;$iRETR\n";
	print OUT ">RETR $kazu[0]\n";
	print S "RETR $kazu[0]\r\n";
	$ans="";
	while() {
		$ans .= $_;
		if($ans =~ /\r\n/){last;}
	}
	print OUT $ans;
	if($ans !~ /^\+OK/) {
		print OUT "!RETR error\n";
		print "RETR error\n";
	} else {
		@anses=split(/\r\n/,$ans,2);
		if(@anses>=2){$ans=$anses[1];} else {$ans="";}
		while() {
			$ans .= $_;
			if($ans =~ /\.\r\n/){last;}
		}
		$ans =~ s/\.\r\n//;
		if(open(MAILFILE,"> mails/$kazu[0].txt")) {
			print MAILFILE $ans;
			close(MAILFILE);
		}
	}
}

&sendquit;
close(OUT);
exit(0);

sub sendquit {
	print ">QUIT\n";
	print OUT ">QUIT\n";
	print S "QUIT\r\n";
	$ans="";
	while() {
		$ans .= $_;
		if($ans =~ /\r\n$/){last;}
	}
	print OUT $ans;
	if($ans !~ /^\+OK/) {
		print OUT "!QUIT error\n";
		print "QUIT error\n";
	}
	close(S);
}
perl (ファイル名) サーバー ユーザー名 パスワード
の形で実行します。
事前にカレントディレクトリにmailsディレクトリを作っておいてください。
実行すると、成功すれば
log.txt・・・実行ログ
list.txt・・・LISTコマンドの結果
mails/(番号).txt・・・受信したメール
というファイルが作られるはずです。
受信したメールの解読まではこのプログラムではしません。

意見、改善点などがあれば遠慮なくコメントを下さい。
なんでもいいのでコメントをいただけると喜びます。
(といってもあまりに非常識なコメントは・・・)
よろしくお願いします。

コメントはまだありません。