@lay:3449l3

# ------------------------------------------------------------
# Listing 3: A version of send-mail.pl that restricts the
# recipient to be in a specified domain

#!/usr/bin/perl -wT

use strict;
use diagnostics;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use Mail::Sendmail;

# ------------------------------------------------------------
# Set up a list of approved domains
my @approved_domains = ('lerner.co.il', 'ssc.com');

# Set up a variable for testing domain match
my $match_found = 0;

# ------------------------------------------------------------
# Create a new instance of CGI
my $query = new CGI;

# Send a MIME header to the user's browser
print $query->header;

# Get the fields from the HTML form
my $sender = $query->param("sender");
my $recipient = $query->param("recipient");
my $message = $query->param("message");

# Make sure that all are filled in
die "Sender, recipient, and message must be filled in!"
    unless ($sender && $recipient && $message);

# Add some advertising to the message
my $footer = "--\nBrought to you by ReuvenMail\n";
$message .= $footer;

# ------------------------------------------------------------
# Iterate through each domain, checking to see if it
# matches the recipient's domain
foreach my $domain (@approved_domains)
{
    if ($recipient =~ m/$domain$/)
    {
	$match_found = 1;
	last;
    }
}

# Send mail only if the domain matched
if ($match_found)
{
    # Create the mail message
    my %mail = (To => $recipient,
		From => $sender,
		Message => $message);

    # Send the message
    if (sendmail %mail) 
    {
	# Send some output to the user's browser
	print $query->start_html(-title => "Success!");

	print "<H1>Success!</H1>\n";
	print "<P>The following message was successfully sent:</P>\n";

	print "<Form method=\"POST\" action=\"\">\n";
	print "<P><HR></P>\n";
	print "<P>Sender: $sender</P>\n";
	print "<P>Recipient: $recipient</P>\n";
	print "<P>Message:<P></P>";
	print "<textarea rows=\"20\" cols=\"60\">";
	print "$message</textarea></P>\n";
	print "<P><HR></P>\n";
	print "</Form>\n";

	print $query->end_html;
    }
    else
    {
	print "Error sending mail: $Mail::Sendmail::error \n";
    }
}

# If the domain was not approved
else
{
    die "Mail was not sent: The recipient's domain is not approved.\n";
}
