【问题标题】:how to send SMTP email in perlperl 如何发送 SMTP 邮件
【发布时间】:2012-06-08 05:24:47
【问题描述】:

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

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

无法在 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;

【问题讨论】:

  • @flo,无需在您编辑的帖子中添加** Edited for formatting。但是,您必须做其他事情。如果可能,请修复帖子中的所有问题。
  • 请考虑使用更高级别的模块,例如Email::Sender 来发送电子邮件。 Here's an example 来自上一个问题。
  • 也使用严格的;使用警告;

标签: perl smtp


【解决方案1】:

变量$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;

【讨论】:

    【解决方案2】:

    您熟悉面向对象的 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;
    

    【讨论】:

      猜你喜欢
      • 2012-04-17
      • 2019-04-22
      • 1970-01-01
      • 2021-03-28
      • 2010-11-22
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      相关资源
      最近更新 更多