#!/usr/bin/perl -W

use strict;

my $headers = {};

my ($current_header, $last_recorded_header) = ("", "");

while (my $line = <STDIN>) {
	last if ($line =~ m/^\s*$/); # END of headers

	if ($line =~ m/^(^\w+): (.*)/) {
		$current_header = lc($1);
		next unless (
			("$current_header" eq "to") or
			("$current_header" eq "cc") or
			("$current_header" eq "bcc")
		);
		chomp (my $value = $2);
		$value =~ s/\s*,\s*$//;
		if ("$current_header" ne "$last_recorded_header") {
			$last_recorded_header = $current_header;
		} else {
			$headers->{"$last_recorded_header"} .= ", ";
		}
		$headers->{"$last_recorded_header"} .= "$value, ";
		next;
	}

	if ($line =~ m/\s+(.*)$/) {
		chomp (my $value = $1);
		$headers->{"$last_recorded_header"} .= "$value";
		next;
	}

	# Should never come here
	die "Invalid headers!\n";
}

my $email_regex_1 = qr/[^@,]+@[^@,]+/;

my $email_regex_2 = qr/(?:"[^"]+(?:\"[^"]*)*")?\s*<[^@]+@[^@]+>/;

my $emails_string = $headers->{"to"};

my @emails = ($emails_string =~ m/\s*($email_regex_1|$email_regex_2)\s*,?/g);

print "Found mail: $_\n" foreach (@emails);

exit(0);

