File: gotmail.pl

package info (click to toggle)
gotmail 0.6.6-6
  • links: PTS
  • area: main
  • in suites: woody
  • size: 100 kB
  • ctags: 18
  • sloc: perl: 581; makefile: 41
file content (766 lines) | stat: -rwxr-xr-x 23,059 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
#!/usr/bin/perl -w
#    GotMail - perl script to get mail from hotmail mailboxes.
#    Copyright (C) 2000 Peter Hawkins <peterhawkins@ozemail.com.au>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#    Please forgive my obvious lack of perl expertise.

use English;
use URI::Escape;
use POSIX qw(tmpnam);
use FileHandle;
use strict;

# Signal handlers:
$SIG{INT} = $SIG{__DIE__} =
	sub {
		print STDERR "Exiting abnormally, cleaning temp files.\n";
		doCleanTempFiles();
		exit(1);
	};

# Hide command line in a "ps" listing;
$0 = '[ gotmail getting new messages ]';
# FIXME: This is, however, completely futile, because curl displays the username and password anyway.  Any suggestions on how to tell curl to hide it's command line? The perl FAQ also reliably informs us that this isn't particularly wonderful security anyway.

# Don't allow others to read our temp files
my($oldumask) = umask(077);

# Constants...
# FIXME: This may have race conditions but do I look like I care? It's better than just /tmp/blah =)
my($tmp_headers) = tmpnam()."gotmail_headers";
my($tmp_cookies) = tmpnam()."gotmail_cookies";
my($tmp_formdata) = tmpnam()."gotmail_form";


my($log) = "/tmp/gotmail_log";
my($gotmail_version) = "0.6.6";
my($gotmail_date) = "2001-07-24";

# Blacklisted hosts. These hosts have known problems with the &raw=0 option.
# If we are told to use this host, we will disregard the request and instead
# use the whitelist host below. If you are having problems getting mail, try
# adding your host to the blacklist. If this improves matters, email me and
# I'll add it to defaults.
my(@host_blacklist) = ("lw3fd.law3.hotmail.msn.com", "lw8fd.law8.hotmail.msn.com");
my(@host_dotnet_blacklist) = ("lc1.law5.hotmail.passport.com", "lc2.law5.hotmail.passport.com", "lc3.law5.hotmail.passport.com");
my($host_known_good) = "lc1.law13.hotmail.passport.com";

# Some option dependant variables
my($conf_proxy)="";
my($conf_proxy_auth)="";
my($login) = "";
my($password) = "";
my($resend_address) = "";
my($conf_folders) = "";
my($conf_folder_directory) = "";
my($conf_only_get_new_messages) = 0;
my($conf_mark_messages_as_read) = 0;
my($conf_delete_messages_after_download) = 0;
my($conf_sendmail) = "";
my($conf_curl) = "";
my($conf_speed_limit) = 0;
my($conf_retry_limit) = 2;
my($conf_verbosity) = 0;  # -1 = silent; 0 = normal; 1 = verbose; 2 = debug spew

# Global variables...
my($host) = ""; # The name of the hotmail server we are talking to...
my($gotconfig) = 0; # Have we found a config file?
my(@cookies) = ();

# Various utility functions
sub dispIntroText()
{
    if ($conf_verbosity >= 0)
    {
        print "Gotmail v".$gotmail_version."    Copyright (C) 2000 Peter Hawkins\n";
	print "Gotmail comes with ABSOLUTELY NO WARRANTY.\n";
	print "This is free software, and you are welcome to redistribute it\n";
	print "under certain conditions; see the file COPYING for details.\n\n";
    }
}

sub dispVersionText()
{
    print "Version information: Gotmail v".$gotmail_version."   Date: ".$gotmail_date."\n";
}

sub dispUsageAndExit()
{
	# We are about to quit, so we want to show the user everything.
	$conf_verbosity = 0;
	dispIntroText();

	print "Usage:\ngotmail [OPTIONS...]\n";

	print "\nOptions:\n";
	print "  -?, --help, --usage         Display this screen\n";
	print "  --version                   Display version information\n";
	print "  -u, --username              Specify your hotmail username (REQUIRED)\n";
	print "  -p, --password              Specify your hotmail password (REQUIRED)\n";
	print "  --proxy host:port           Specify an HTTP proxy to use. Format is\n" .     "                              host:port - eg: localhost:3128\n";
	print "  --proxy-auth user:password  Specify authentification details for the HTTP\n" . "                              proxy.\n";
	print "  -f, --forwarding-email      Specify an email address to forward to. If a\n". "                              forwarding address is not given, messages will\n"."                              be saved to disk\n";
	print "  --folders \"folders\"         Only get these folders (list of folders in quotes)\n";
	print "  --folder-directory /my/dir  Download messages into this directory\n";
	print "  --only-new-messages         Only unread messages will be retrieved\n";
	print "  --mark-messages-as-read     Messages will be marked as read once downloaded\n";
	print "  --delete-messages           Messages will be deleted after download\n";
	print "  --retry-limit max_tries     Maximum number of attempts to download a message\n";
	print "  --speed-limit               Throttle back rate of giving messages to sendmail\n";
	print "  --silent                    Do not print messages\n";
	print "  -v, --verbose               Verbosely print messages\n";
	print "  --debug                     Print debug output\n";
	exit();
}

# Display some text to the screen, and log it, if we are in debug mode.
sub dispText($)
{
    my($text) = @_;

    if ($conf_verbosity >= 0) {
	print $text;
    }

    if ($conf_verbosity > 1) {
	my($out) = new FileHandle ">> $log" || return;
	print $out $text;
	close $out;
    }
}

#
# Parse ~/.gotmailrc
#
# Inserted code to parse ~/.gotmailrc
# This *should* hopefully be a little secure than specifying your
# username and password on the command line.
# parseArgs() is called afterwards, so you can override any settings.
# Thanks to Patrick Froede
sub parseConfig {
	# Open the config file, otherwise bail out of this subroutine
	open(RCFILE, $ENV{"HOME"} . "/.gotmailrc") || return;

	# Parse the file
	while (<RCFILE>) {
		next if ($_ =~ /^#/);
		if ($_ =~ /user=(.+)/i) {
			$login = $1;
		} elsif ($_ =~ /pass=(.+)/i) {
			$password = $1;
		} elsif ($_ =~ /proxy=(.+)/i) {
			if ($1 !~ /^no$/i) {
				$conf_proxy = $1;
			}
		} elsif ($_ =~ /proxy_auth=(.+)/i) {
			if ($1 !~ /^no$/i) {
				$conf_proxy_auth = $1;
			}
		} elsif ($_ =~ /forward=(.+)/i) {
			if ($1 !~ /^no$/i) {
				$resend_address = $1;
			}
		} elsif ($_ =~ /folders=(.+)/i) {
				$conf_folders = $1;
		} elsif ($_ =~ /folder_directory=(.+)/i) {
				$conf_folder_directory = $1;
				if ($conf_folder_directory !~ /\/$/) {
					# Make sure it has a trailing slash
	                        	$conf_folder_directory.="/";
				}
		} elsif ($_ =~ /markread=(.+)/i) {
			if ($1 !~ /^no$/i) {
				$conf_mark_messages_as_read = 1;
			}
		} elsif ($_ =~ /delete=(.+)/i) {
			if ($1 !~ /^no$/i) {
				$conf_delete_messages_after_download = 1;
			}
		} elsif ($_ =~ /onlynew=(.+)/i) {
			if ($1 !~ /^no$/i) {
				$conf_only_get_new_messages = 1;
			}
		} elsif ($_ =~ /speedlimit=(.+)/i) {
			if ($1 !~ /^no$/i) {
				$conf_speed_limit = 1;
			}
		} elsif ($_ =~ /retrylimit=([0-9]+)/i) {
				$conf_retry_limit=$1;
		} elsif ($_ =~ /silent=(.+)/i) {
			if ($1 !~ /^no$/i) {
				$conf_verbosity = -1;
                        }
                }
	}

	# Make a note that we obtained some configs from the options file
	$gotconfig = 1;
	close(RCFILE);
}

# Parse the command line
sub parseArgs()
{
	if (!@ARGV && ($gotconfig == 0))  # If we have a config file, we don't care if there aren't any arguments...
	{
		dispUsageAndExit();
	}
	while(@ARGV) { 
		my($element)=shift(@ARGV);
		if (($element =~ /-\?/i) || ($element =~ /--help/i) || ($element =~ /--usage/i))
		{
			dispUsageAndExit();
			exit();
		}
		elsif ($element =~ /--version/) {
			dispVersionText();
			exit();
		}
		elsif (($element =~ /^-u$/i) || ($element =~ /--username/i))
		{
			if (@ARGV) {
				$login = shift(@ARGV);
			} else {
				dispUsageAndExit();
			}
		}
		elsif (($element =~ /^-p$/i) || ($element =~ /--password/i))
		{
			if (@ARGV) {
				$password = shift(@ARGV);
			} else {
				dispUsageAndExit();
			}
		}
		elsif ($element =~ /--proxy/i)
		{
			if(@ARGV) {
				$conf_proxy = shift(@ARGV);
			} else {
				dispUsageAndExit();
			}
		}
		elsif ($element =~ /--proxy-auth/i)
		{
			if(@ARGV) {
				$conf_proxy_auth = shift(@ARGV);
			} else {
				dispUsageAndExit();
			}
		}
		elsif ($element =~ /--folder-directory/i)
		{
			if(@ARGV) {
				$conf_folder_directory = shift(@ARGV);
			} else {
				dispUsageAndExit();
			}
			if ($conf_folder_directory !~ /\/$/) {
				# Make sure it has a trailing slash
                        	$conf_folder_directory.="/";
			}
		}
		elsif (($element =~ /^-f$/i) || ($element =~ /--forwarding-email/i)) {
			if (@ARGV) {
				$resend_address = shift(@ARGV);
			} else {
				dispUsageAndExit();
				exit;
			}
		}
		elsif ($element =~ /^--folders$/i) {
			if (@ARGV) {
				$conf_folders = shift(@ARGV);
			} else {
				dispUsageAndExit();
				exit;
			}
		}
		elsif ($element =~ /^--retry-limit$/i) {
			if (@ARGV) {
				$conf_retry_limit = shift(@ARGV);
			} else {
				dispUsageAndExit();
				exit;
			}
		}
		elsif ($element =~ /--only-new-messages/i) {
			$conf_only_get_new_messages = 1;
		}
		elsif ($element =~ /--mark-messages-as-read/i) {
			$conf_mark_messages_as_read = 1;
		}
		elsif ($element =~ /--delete-messages/i) {
			$conf_delete_messages_after_download = 1;
		}
		elsif ($element =~ /--speed-limit/i) {
			$conf_speed_limit = 1;
		}
		elsif ($element =~ /--silent/i) {
			$conf_verbosity = -1;
		}
		elsif ($element =~ /--debug/i) {
			$conf_verbosity = 2;
		}
		elsif (($element =~ /--verbose/i) || ($element =~ /^-v$/i)) {
			$conf_verbosity = 1;
		}
		else {
			dispText("Unrecognised option $element\n");
			dispUsageAndExit();
		}
	}

	if (($login eq "") || ($password eq ""))
	{
		dispText("A username and password are REQUIRED.\n");
		dispUsageAndExit();
	}
}

# Clean up any temporary files
sub doCleanTempFiles()
{
	if (-e $tmp_headers) {
		unlink($tmp_headers)
		  or warn "Could not unlink tmp header: $!\n";
	}
	if (-e $tmp_cookies) {
		unlink($tmp_cookies)
		  or warn "Could not unlink tmp cookie: $!\n";
	}
	if (-e $tmp_formdata) {
		unlink($tmp_formdata)
		  or warn "Could not unlink tmp formdata: $!\n";
	}
}

sub doCleanOtherFiles()
{
	if (-e $log) 	     { unlink($log); }
}

# Check all the required programs are installed.
sub doCheckPrograms()
{
	if ($conf_verbosity > 1) {
		dispText("System version is: ".$OSNAME."\n");
		dispText("Perl version is:   ".$PERL_VERSION."\n");
	}


	if (-x "./curl") { $conf_curl = "./curl"; }
	else { $conf_curl = "curl"; }
	if ($conf_verbosity > 1) { dispText("Curl version is:   ".`$conf_curl --version`."\n"); }

	# Try looking for sendmail in a few common places.
	$conf_sendmail = "sendmail";
	if (-x "/usr/sbin/sendmail") { $conf_sendmail = "/usr/sbin/sendmail" }
	elsif (-x "/usr/lib/sendmail") { $conf_sendmail = "/usr/lib/sendmail" }
}

# Grep any cookies from the header file into the cookies file.
sub parseHeaders($)
{
	my ($getCookies) = @_;
	my $redirector = "";
	my($in) = new FileHandle "< $tmp_headers" || return;
	while (<$in>)
	{
		if (m/^Set-Cookie: ([A-Za-z0-9]*)=/i) {
			# Remove any previous setting for this cookie
			@cookies = grep { !/$1/ } @cookies;

			# Make cookies globally applicable. Evil. =)
			s/domain=([^\;]+)\;/domain=.com\;/;

			push(@cookies, $_);
		}
		if (m/^Location: (\S+)\s/) {
			$redirector = $1;
		}
	}
	close($in);

	if ($getCookies)
	{
		# Dump the cookie list into a file so curl can read it.
		my($out) = new FileHandle "> $tmp_cookies" || return;
		my $cookiestr = join "", @cookies;
		print $out $cookiestr;
		if ($conf_verbosity > 1)
		{
			dispText("Cookies are $cookiestr\n");
		}
		close($out);
	}

	return $redirector;
}


# Fetch a given page using curl
# The parameters taken are the URL, any data to be posted in a POST,
# whether we are to follow HTTP redirects, and whether we should send and receive
# cookies, whether we should only get the headers for this page and not the body.
sub getPage($$$$$)
{
	my($url, $params, $follow_forward, $cookies, $headers_only) = @_;

	# If the host is dotnet-listed, use the known good host instead
	if ($url =~ m/http:\/\/(\S+?)\//i) {
		$host = $1;
	}
	if (grep(/$host/i, @host_dotnet_blacklist))	{
		if ($conf_verbosity > 0) {
			dispText "Avoid .NET: Replace $host with $host_known_good\n";
		}
		$url =~ s/$url/$host_known_good/;
	}

	if ($conf_verbosity > 0) {
		dispText "FETCH: $url\n";
	}
	
	# Set up the options string...
	my($options) = "";
	if ($conf_proxy) { $options .= "--proxy ". $conf_proxy . " "; }
	if ($conf_proxy_auth) { $options .= "--proxy-user ". $conf_proxy_auth . " "; }
	if ($cookies != 0) { $options .= "-b $tmp_cookies " }
	if ($params ne "") { $options .= "--data \"$params\" " }
	if ($headers_only) { $options .= "-I " }
	if ($conf_verbosity <= 0) { $options .= "-s -S " }
	# Get rid of any trailing space on options.. Just for neatness.
	$options =~ s/ $//;

	my($cmdline) = "$conf_curl \"$url\" $options -i -m 600 -D $tmp_headers -A \"Mozilla/4.73 [en] (Win98; I)\"";
	if ($conf_verbosity > 1) {
	 	$cmdline .= "| tee -a $log"; # Copy output to the logfile
		dispText("command line: $cmdline\n");
	}
	my $tries = 1;
	my(@tmp_page) =  `$cmdline`;

	# Retry at most $conf_retry_limit times if we fail.
	while (!@tmp_page && !$headers_only && $tries <= $conf_retry_limit) {
		dispText("An error was encountered getting the page, retrying [$tries/$conf_retry_limit]...\n");
    $tries++;
		@tmp_page = `$cmdline`;
	}
	if (!@tmp_page && !$headers_only && $tries >= $conf_retry_limit) {
		die("An error was encountered getting the page. Command was $cmdline"); 
	}

	my $redir = parseHeaders($cookies);

	# If we have been asked to follow Location: headers
	if ($follow_forward)
	{
    if ($redir ne "")
		{
			if ($conf_verbosity > 1) { dispText("Following redirect to $redir\n"); }
			return &getPage($redir, "", $follow_forward, $cookies, $headers_only);
		}
	}

	if ($conf_verbosity > 0) { dispText "\n"; }

	return @tmp_page;
}

# Do the HotMail login process - log in until we have the URL of the inbox.
sub doLogin()
{
	dispText("Getting hotmail index page...\n");
	my(@index_page) = getPage("http://www.hotmail.com/", "", 1, 0, 0);

	# Find the form "ACTION" parameter...
	my($login_script) = "";

	my $page = join "", @index_page;
	if ($page =~ m/<form.*action=\"(\S+)\".*>/i) {
		$login_script = $1;
	}

	if ($login_script eq "") {
		die "Page doesn't contain any form action field!\n";
	}

	my($FORMFILE) = new FileHandle "> $tmp_formdata" || die "Couldn't open formdata file: $!\n";
	print $FORMFILE ("login=". uri_escape($login, "^A-Za-z"). "\&passwd=" . uri_escape($password, "^A-Za-z"));
	close $FORMFILE;
	my($params) = "\@$tmp_formdata";

	dispText("Logging in...\n");
	my(@login_page) = getPage($login_script, $params, 0, 1, 0);

	# Find where they are sending us now... 
	my($redirect_location) = "";
	$page = join "", @login_page;
	
	if ($page =~ m/<meta(.*)content=\"(.*)url=(\S+)\">/i) {
		$redirect_location = $3;
	}

	if ($redirect_location eq "")
	{
		die("Hotmail's page structure has changed!\n");
	} elsif ($redirect_location =~ /loginerr/i)
	{
		die("There was an error logging in. Please check your username and password are correct.\n");
	}
	
	if ($redirect_location =~ m/http:\/\/(\S+)\/cgi(\S+)/i)
	{
		$host = $1;
	} else {
		die ("Could not parse redirect location");	
	}
	
	dispText("Following redirect...\n");
	my(@redirect_page) = getPage($redirect_location, "", 0, 1, 0);

	# Find where the inbox is located... 
	my($inbox_location) = "";
	$page = join "", @redirect_page;
	if ($page =~ m/Location: (\S+)/i) {
		$inbox_location = $1;
	}
	elsif ($page =~ /unavailable/i) {
		die("Hotmail is reporting that your account is temporarily unavailable. Please try again later.");
	}
	if ($inbox_location eq "")
	{
		die("Hotmail's page structure has changed!\n");
	}
	return $inbox_location;
}


sub doSaveEmail($$)
{
	my ($output, $email) = @_;

	# restore umask to whatever user had before
	umask($oldumask);
	my($OUT) = new FileHandle ">> $output";

	if (! defined ($OUT))
	{
		die("Unable to open $output.");
	}

	print $OUT $email;

	$OUT->close();
}

sub doResendEmail($$)
{
	my($destaddr, $email) = @_;

	my($OUT) = new FileHandle "| $conf_sendmail $destaddr";
	if (! defined ($OUT))
	{
		die("Unable to open sendmail - was using $conf_sendmail $destaddr.");
	}
	# Dump the message to sendmail.
	print $OUT $email;

	$OUT->close();
	if ($conf_speed_limit) { sleep(1); }
}

sub getEmail($$)
{
	my($url, $stripmboxheader ) = @_;
	my(@output) = ();

	dispText("Getting email messages...\n");

	# If the host is blacklisted, go through the hotmail cookie redirection maze to get a raw message
	# Check for blacklisted host. Work around for dud hosts.
	if (grep(/$host/i, @host_blacklist))
	{
            my $saferd_url = "http://$host/cgi-bin/saferd?_lang=\&hm___tg=".uri_escape("http://$host_known_good/cgi-bin/getmsg", "^A-Za-z0-9")."\&hm___qs=".uri_escape($url."\&raw=0", "^A-Za-z0-9")."\&hm___fl=attrd";
  	    my @saferd_page = getPage($saferd_url,"",0,1,0);
	    my $mail_url = join "", grep(/<frame name=\"attachment\"/, @saferd_page);
	    $mail_url =~ m/<frame(.*)src=\"(\S+)\"/i;
	    $url = $2;

	    if ($url eq "")
	    {
	    	    die("Error in email redirection - ".join("",@saferd_page));
	    }
	}
	else
	{
		$url = "http://$host/cgi-bin/getmsg?".$url."\&raw=0";
	}
	
	my(@email_page) = getPage($url, "", 1, 1, 0);

 	my $emailstr = join "", @email_page;
	if ($emailstr !~ /pre/) {
  	    die("Unable to download email message - $emailstr\n");
	}

	# Get everything between the <pre> </pre> tags 
 	@email_page = split(/<pre>|<\/pre>/, $emailstr);
	if (@email_page!=3)
	{
	    die("Unable to download email message - $emailstr\n");
	}
        $_ = $email_page[1];

	s/^(\s*)//;
	if ($stripmboxheader)
	{
 	    s/^From (.*)\n//;
	}

	# Strip any HTML artifacts from the message body.
	s/&amp;/&/g;
	s/&lt;/</g;
	s/&gt;/>/g;
	s/&quot;/\"/g;
	return $_;
}

# Get the messages from a folder called $foldername at $url
sub getFolder($$$)
{
	my($foldername, $url, $page) = @_;

	# Get the folder in newest first order
	dispText("Loading folder \"$foldername\" page $page...\n");
        # "sort=rNew" = newest first 
	my(@folder) = getPage("http://$host/cgi-bin/HoTMaiL?$url\&sort=rNew", "", 1, 1, 0);

	# Find the location of the "Next page" link
	my $next_page_str = join("", grep(/Next Page/i, @folder));

	# Redo the list on a table row by table row basis
	my @messages = split(/<tr[^>]*>|<\/tr>/i, join("",@folder)); 
	@messages = grep(/<a href=\"\/cgi-bin\/getmsg\?/i, @messages);

	# Get the messages in this folder...
	foreach my $item (@messages)
	{
		if ($item =~ m/<a href=\"\/cgi-bin\/getmsg\?(\S+)\">/i) {
			my $msg_url = $1;
			# Since the folder is in newest first order, if we are only getting new messages, and this is not a new message, we can stop here.
			if ($conf_only_get_new_messages && ($item !~ /newmail/i)) {
				return;
			}

			# Are we resending or saving?
			if ($resend_address eq "")
			{
				my($output) = getEmail($msg_url, 0);
				doSaveEmail($conf_folder_directory.$foldername, $output);
			} else {
				my($output) = getEmail($msg_url, 1);
				doResendEmail($resend_address, $output);
			}

			if ($conf_delete_messages_after_download)
			{
				dispText("Deleting message...\n");
				getPage("http://$host/cgi-bin/nextprev?".$msg_url."\&action=move\&tobox=trAsH", "", 0, 1, 1);
			}
			elsif ($conf_mark_messages_as_read)
			{
				dispText("Marking message as read...\n");
				&getPage("http://$host/cgi-bin/getmsg?".$msg_url, "", 0, 1, 1);
			}
		}	
	}

	
	# If a "next page" exists, let's go there...
	if ($next_page_str =~ m/<a href=\"\/cgi-bin\/HoTMaiL\?(\S+)\">Next Page<\/a>/) {
		&getFolder($foldername, $1, $page + 1);
	}
}

# Get a list of the folders we have to deal with and parse them one by one.
sub doGetFolders($)
{
	my ($inbox_location) = @_;
	dispText("Loading main display...\n");
	if ($inbox_location !~ m/^http/)
	{
	    $inbox_location = "http://$host/cgi-bin/".$inbox_location;
	}
	my(@inbox_page) = getPage($inbox_location, "", 0, 1, 0);

	# Ok, we have the location of the inbox. Where's the master list of folders?
	my($folder_index_url) = "";
	foreach my $item (@inbox_page)
	{
		if ($item =~ m/<a(.*)href=\".*\/cgi-bin\/folders\?(\S+)\"/i)
		{
			$folder_index_url = $2;
		}
	}

	if ($folder_index_url eq "") {
		die("Could not isolate folder index location\n");
	}

	# Ok let's get the folder list!
	dispText("Loading folder list...\n");
	my @folder_list = getPage("http://$host/cgi-bin/folders?$folder_index_url", "", 0, 1, 0);
	
	# Join the page into one big string, and split it into bits that interest us
 	my $onestr = join "", @folder_list;
 	$onestr =~ s/\n/ /g;
 	@folder_list = grep { /<td><a\s*href=\"\/cgi-bin\/HoTMaiL\?/ }
		split(/(<tr[^>]*>|<\/tr>)/, $onestr);

	foreach my $item (@folder_list)
	{
		if ($item =~ m/<a(.*)href=\"\/cgi-bin\/HoTMaiL\?(\S+)\"\s*><font class="Wf">(.+)<\/font><\/a>/) {
			my($url) = $2;
			my($name) = $3;	
			# We assume the presence of a <b> indicates new mail.
			if ((!$conf_only_get_new_messages) || ($item =~ /<b>/)) {
				# Check that this actually _is_ a folder name, without any html tags... Also makes sure we are not getting the trash (it looks really stupid when we download a message, delete it, and then download it again from the trash and delete it into the trash yet again =)
				if ( (!($name =~ /[<>]/)) && (!($name =~ /Trash Can/i))  && (!($name =~ /Sent Messages/i)) && (!($name =~ /Drafts/i)) && (($conf_folders eq "") || ($conf_folders =~ /$name/i)) )
				{
					getFolder($name, $url, 1);
				}
			}
		}
	}
}

# Make sure we end up cleaning up after ourselves
#END { doCleanTempFiles(); }

parseConfig();
parseArgs();
dispIntroText();
doCheckPrograms();
doCleanOtherFiles();
my($inbox_location) = doLogin();
doGetFolders($inbox_location);
dispText("\nAll done!\n");
doCleanTempFiles();

exit;