如何在perl中发送SMTP电子邮件

时间:2012-06-07 17:06:26

标签: perl smtp

以下是我发送邮件从我的邮件主机发送到我个人的电子邮件地址以及我收到的错误。

有人可以帮助我解决为什么我们收到错误:

  

无法在cmm_ping.pl第2行的未定义值上调用方法“mail”。

use Net::SMTP;
$smtp->mail("jo-sched@abcd.com");
$smtp->recipient("Myname@XXX-XXXX.com");
$smtp->datasend("From: jo-sched@abcd.com");
$smtp->datasend("To: Myname@xxxx-xxxxxx.com");
$smtp->datasend("Subject: This is a test");
$smtp->datasend("\n");
$smtp->datasend("This is a test");
$smtp->dataend;
$smtp->quit;

2 个答案:

答案 0 :(得分:3)

尚未定义变量$smtp。看看usage examples of Net::SMTP。这个例子几乎完成了你的代码应该做的事情:

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;

答案 1 :(得分:3)

您熟悉面向对象的Perl如何工作?

为了使用面向对象的Perl模块,您必须首先创建该类类型的对象。通常,这是通过new方法完成的:

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

现在,$smtp是类Net::SMTP对象。基本上,它是对glob的引用,您可以在其中存储数据结构(您发送给谁,您的消息等)。然后Perl可以在方法调用期间使用这些信息(它们只是Net :: SMTP包的子程序)。

这是我写的程序中的一个例子:

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;