#!/usr/bin/perl -w

use strict;

###############################
# Send Email
###############################
sub sendEmail() {
    my $sender = shift @_;
    my $recipient = shift @_;
    my $subject = shift @_;
    my $message = shift @_;

    if (! (validEmail($sender)) && (validEmail($recipient)) ) {
	return "Could not send you your email.  Your email address was invalid";
    }

    if (! open(MAIL, "| /usr/sbin/sendmail -t") ) {
	return "Could not send you your email: (1)$!";
    }
    
    $message =~ s/\cM//g;
    print MAIL "To: $recipient\n";
    print MAIL "From: $sender\n";
    print MAIL "Subject: $subject\n\n";
    print MAIL "$message\n";
    
    if (! close(MAIL) ) {
	return "Could not send you your email: (2)$!";
    }

    return;
}
### End sendEmail();

################################ HELPER FUNCTIONS #############################

################################################
# Verifies if email address is in correct format
################################################
sub validEmail {
    my $email = shift @_;
    
    if ($email =~ /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/) {
	return 0;
    }
    if ($email !~ /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/) {
	return 0;
    }
    
    return 1;
}
### End validEmail();

1;
