Article Listing 1 dec2006.tar

Listing 1 Sample auto-responder program

#!/usr/bin/perl

# natabot -- Let people know folks have moved on
#
# Copyright (C) 2006 Hal Pomeranz/Deer Run Associates, hal@deer-run.com
# All rights reserved.  Permission to distribute freely under the 
# same terms as Perl as long as this copyright and all other comments
# are preserved

# How to use this script:
#
# Assuming user "smith" has changed jobs and is now "smith@other.org",
# just create an alias:
#
#    smith: "|/usr/local/bin/natabot smith@other.org"
#
# The new address argument is always optional.

$sendmail = '/usr/sbin/sendmail';        # path to Sendmail binary

# Read the first line of the incoming message and get the return 
# address from this first line.  Quit silently if we can't 
# if message is from MAILER-DAEMON (aka '<>'). Quit noisily if we 
# detect shell metacharacters in the address.
#
$envelope = <STDIN>;
($sender_addr) = $envelope =~ /^From\s+(\S+)/;
exit(0) if ($sender_addr eq '<>' || 
            $sender_addr =~ /^mailer-daemon/i)
die "Hostile address: $sender_addr\n" 
    unless ($sender_addr =~ /^[^<>|&;\\]+@[-\w.]+$/);

# Now read in the rest of the headers.  Quit silently if we find a
# Precedence: header with value junk, list, or bulk.  We've reached
# the end of the headers when we hit a blank line.
#
while (<STDIN>) {
    last if (/^$/);
    exit(0) if (/^Precedence:\s+(list|junk|bulk)/);
    push(@headers, $_);
}

# OK, time to start sending mail.  Again we try to avoid people 
# messing with shell metachars in the $from address by opening a 
# pipe to Sendmail the hard way (which doesn't invoke the shell).
#
# Note that we're sending our bounce message from MAILER-DAEMON.
# Theoretically this should mean that any autoresponders that get
# our message will not generate a message of their own.
#
$pid = open(MAIL, "|-");


# The child executes this block.
unless ($pid) {
    exec(/usr/sbin/sendmail, '-f', '<>', $sender_addr);
    die "exec() failed: $!\n";
}

# If we get here, we're the parent process.
die "fork() failed: $!\n" unless (defined($pid));

# Print some opening headers (including our own Precedence: header) 
# and initial chat into the message.
#
print MAIL <<"EOMesg";
From: MAILER-DAEMON
To: $sender_addr
Precedence: junk
Subject: FYI -- Invalid Address

You have sent mail to an address which is no longer valid.
EOMesg

# If we have a new address argument, print that.  Then push the 
# headers and the rest of the incoming message into the message 
# we're sending back.
#
print MAIL "The individual's new address is: $ARGV[0]\n" 
    if (length($ARGV[0]));
print MAIL "\nYour message is returned below for your convenience.\n\n";
print MAIL @headers;
print MAIL "\n";
while (<STDIN>) { print MAIL; }

# Close the pipe to the Sendmail program and exit quietly
#
close(MAIL);
exit(0);