Skip to content

Instantly share code, notes, and snippets.

@oshiro-kazuma
Created October 21, 2012 16:37
Show Gist options
  • Save oshiro-kazuma/3927524 to your computer and use it in GitHub Desktop.
Save oshiro-kazuma/3927524 to your computer and use it in GitHub Desktop.
perlでgmailに接続

usage

$ perl imapFetch.pl imap.gmail.com user password

#!/usr/bin/env perl
use Net::IMAP::Client;
use Data::Dumper;
use strict;
use warnings;
my $imap = Net::IMAP::Client->new(
server => $ARGV[0],
user => $ARGV[1],
pass => $ARGV[2],
ssl => 1,
port => 993
) or die "Could not connect to IMAP server";
# ログイン
$imap->login or die($imap->last_error);
# INBOXを選択
$imap->select('INBOX') or die($imap->last_error);
# メールをFetch
my $data = $imap->fetch('*', 'BODY.PEEK[]');
# 配列の場合
if( ref($data) eq 'ARRAY' ){
foreach my $mail (@$data) {
print $mail->{'UID'};
print $mail->{'BODY[]'};
createEml($mail->{'UID'}, $mail->{'BODY[]'});
}
# 配列じゃない場合
} else{
print $data->{'UID'};
print $data->{'BODY[]'};
createEml($data->{'UID'}, $data->{'BODY[]'});
}
# 終了
$imap->quit;
# emlファイル生成
sub createEml {
my $uid = shift;
my $body = shift;
# 保存フォルダ作成
if (!-d $ARGV[3]){
mkdir $ARGV[3];
}
my $emlDir = $ARGV[3] . '/' . $ARGV[1];
if (!-d $emlDir){
mkdir $emlDir;
}
# eml保存先
my $eml = $emlDir . '/' . "${uid}.eml";
open( my $FH, ">", $eml )
or die "Cannot open file for write: $!";
print $FH $body;
close $FH;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment