How about testing if STDIN is a tty - if yes, the script is run from the command line. If not, it's a CGI or the e-mail wrapper. CGI sets several HTTP_* variables, check one of these. If set, it's CGI. If not, e-mail wrapper.
# Note - not very thoroughly tested
if (-t STDIN) {
# command-line
} elsif (defined $ENV{SERVER_NAME}) {
# CGI - I used SERVER_NAME, as it _should_ be set
} else {
# e-mail
}
Now I can't guarantee how portable this is, as I didn't test the e-mail part at all - and I can only test Win2K and FreeBSD. Good luck!