user1411254
user1411254

Reputation: 139

how to send SMTP email in perl

Below is what I wrote to send an email from my mailhost to my individual email address and the error I'm getting.

Could someone please help me with why we are getting the error:

Can't call method "mail" on an undefined value at cmm_ping.pl line 2.

use Net::SMTP;
$smtp->mail("[email protected]");
$smtp->recipient("[email protected]");
$smtp->datasend("From: [email protected]");
$smtp->datasend("To: [email protected]");
$smtp->datasend("Subject: This is a test");
$smtp->datasend("\n");
$smtp->datasend("This is a test");
$smtp->dataend;
$smtp->quit;

Upvotes: 2

Views: 11576

Answers (2)

David W.
David W.

Reputation: 107040

Are you familiar with how Object Oriented Perl works?

In order to use an object oriented Perl module, you have to first create an object of that class type. Normally, this is done via the new method:

my $smtp = Net::SMTP->new($mailhost);

Now, $smtp is an object of class Net::SMTP. Basically, it's a reference to a glob where you can store your data structure (who are you sending to, your message, etc.). Then Perl can use this information during method calls (which are just subroutines that are part of the package Net::SMTP).

Here's an example from a program I wrote:

use Net::SMTP;

my $smtp = Net::SMTP->new(
    Host  => $watch->Smtp_Host,
    Debug => $debug_level,
);

if ( not defined $smtp ) {
    croak qq(Unable to connect to mailhost "@{[$watch->Smtp_Host]}");
}

if ($smtp_user) {
    $smtp->auth( $watch->Smtp_User, $watch->Smtp_Password )
        or croak
        qq(Unable to connect to mailhost "@{[$watch->Smtp_Host]}")
        . qq( as user "@{[$watch->Smtp_User]}");
}

if ( not $smtp->mail( $watch->Sender ) ) {
    carp qq(Cannot send as user "@{[$watch->Sender]}")
        . qq( on mailhost "@{[$watch->Smtp_Host]}");
    next;
}
if ( not $smtp->to($email) ) {
    $smtp->reset;
    next;    #Can't send email to this address. Skip it
}

#
# Prepare Message
#
# In Net::SMTP, the Subject and the To fields are actually part
# of the message with a separate blank line separating the
# actual message from the header.
#
my $message = $watch->Munge_Message( $watcher, $email );
my $subject =
    $watch->Munge_Message( $watcher, $email, $watch->Subject );

$message = "To: $email\n" . "Subject: $subject\n\n" . $message;

$smtp->data;
$smtp->datasend("$message");
$smtp->dataend;
$smtp->quit;

Upvotes: 3

Gnosophilon
Gnosophilon

Reputation: 1369

The variable $smtp has not yet been defined. Take a look at the usage examples of Net::SMTP. This example pretty much does what your code shall do:

use Net::SMTP;

$smtp = Net::SMTP->new('mailhost');

$smtp->mail($ENV{USER});
$smtp->to('postmaster');

$smtp->data();
$smtp->datasend("To: postmaster\n");
$smtp->datasend("\n");
$smtp->datasend("A simple test message\n");
$smtp->dataend();

$smtp->quit;

Upvotes: 3

Related Questions