· 8 years ago · May 30, 2018, 04:42 PM
1#!/usr/bin/perl -w
2
3#GSScraper.pl
4
5# GMail Sent Scraper 2010, MrMutation.com
6# Released under the do-with-what-you-will license
7# THIS SOFTWARE IS PROVIDED AS IS WITH NO WARRANTY EXPRESSED OR IMPLIED
8
9# import packages
10use Mail::IMAPClient;
11use IO::Socket::SSL;
12
13my $nArgs = $#ARGV + 1;
14
15if( $nArgs < 2){
16 die "Usage: perl GSScraper.pl USERNAME PASSWORD OUTPUTFILE[optional, will be overwritten]\n\n";
17};
18
19
20# ~^~^~^~^~ You can CHANGE THIS ~^~^~^~^~
21my $user = $ARGV[0] . "\@gmail.com";
22my $pass = $ARGV[1];
23my $writeToFile = 0;
24my $fileout = "";
25
26if($nArgs > 2){
27 my $fileout = $ARGV[2];
28 print $fileout . "\n";
29 if($fileout){
30 $writeToFile = 1;
31 };
32};
33
34
35# You probably want to keep this
36my $host = 'imap.gmail.com';
37
38# You might need to change this if you have some weird folder layout
39my $folder ="[Gmail]/Sent Mail";
40
41
42# ~^~^~ Don't change anything from here down unless you know what you are doing! ~^~^~
43
44
45# Connect to the IMAP server via SSL
46my $socket = IO::Socket::SSL->new(
47 PeerAddr => $host,
48 PeerPort => 993,
49 )
50 or die "socket(): $@";
51
52# Create a client attached to the SSL socket.
53my $client = Mail::IMAPClient->new(
54 Socket => $socket,
55 User => $user,
56 Password => $pass,
57 )
58 or die "new(): $@";
59
60# Check if we're auth'd
61print "You're authenticated.\n" if $client->IsAuthenticated();
62
63# Select sent folder
64$client->select($folder) or die "\nYour folder could not be selected: $@\n";
65
66print "Scraping sent items.\n";
67
68# Get all the msgs in the sent folder
69my $msgs = $client->messages or die "Error in messages: $@\n";
70
71my @contacts = ();
72
73# Parse the msgs to extract the "To" field, add them to our array
74for my $h (
75 values %{ $client->parse_headers( $msgs , "To") } )
76 {
77 push(@contacts, map { "$h->{$_}[0]\n"} keys %$h );
78 }
79
80# Remove duplicate entries
81my %chash = map { $_, 1 } @contacts;
82@contacts = keys %chash;
83
84# Open our output file
85if($writeToFile){
86 open(OPFILE, '>' . $fileout) or die "Output file could not be opened.";
87};
88
89#Print them
90foreach (@contacts) {
91 # To the output file
92 if($writeToFile){
93 print OPFILE $_;
94 };
95 # To standard out
96 print $_;
97}
98
99
100# We're done
101$client->logout();
102
103close(OPFILE);