如何使用MIME :: Lite perl检查上次发送的电子邮件是否已成功发送

时间:2014-09-20 15:09:20

标签: perl email mime

我想用perl代码发送电子邮件。所以我使用了MIME::Lite模块。

如果我删除了last_send_successful支票,我可以按照自己的意愿发送电子邮件,否则我会收到下面提到的错误。我想知道电子​​邮件是否已成功发送。以下是我使用的代码段。

sub sendEmailWithCSVAttachments {
    my $retries        = 3;
    my $retry_duration = 500000;    # in microseconds
    my $return_status;
    my ( $from, $to, $cc, $subject, $body, @attachments_path_array );

    $from                   = shift;
    $to                     = shift;
    $cc                     = shift;
    $subject                = shift;
    $body                   = shift;
    @attachments_path_array = shift;

    my $msg = MIME::Lite->new(
        From    => $from,
        To      => $to,
        Cc      => $cc,
        Subject => $subject,
        Type    => 'multipart/mixed'
    ) or die "Error while creating multipart container for email: $!\n";

    $msg->attach(
        Type => 'text',
        Data => $body
    ) or die "Error while adding text message part to email: $!\n";

    foreach my $file_path (@attachments_path_array) {

        my $file_name = basename($file_path);
        $msg->attach(
            Type        => 'text/csv',
            Path        => $file_path,
            Filename    => $file_name,
            Disposition => 'attachment'
        ) or die "Error while adding attachment $file_name to email: $!\n";
    }

    my $sent = 0;
    while ( !$sent && $retries-- > 0 ) {

        eval { $msg->send(); };

        if ( !$@ && $msg->last_send_successful() ) {
            $sent = 1;
        } else {
            print "Sending failed to $to.";
            print "Will retry after $retry_duration microseconds.";
            print "Number of retries remaining $retries";
            usleep($retry_duration);
            print "Retrying...";
        }
    }

    if ($sent) {
        my $sent_message = $msg->as_string();
        print "Email sent successfully:";
        print "$sent_message\n";
        $return_status = 'success';
    } else {
        print "Email sending failed: $@";
        $return_status = 'failure';
    }
}

我得到的错误是:

Can't locate object method "last_send_successful" via package "MIME::Lite"

这意味着此方法不存在。但它在我使用的参考文献中给出。

  1. 我是否遗漏了某些内容,或者是否可以选择检查上次发送是否成功或我使用的引用是否错误?

  2. 这个检查是否冗余,因为我已经在使用eval块?

  3. 使用eval会捕获未送达电子邮件的错误吗? (很可能没有,但想确认)

  4. 如何确保电子邮件与MIME :: Lite一起发送?

1 个答案:

答案 0 :(得分:5)

您不需要使用eval块或做任何花哨的事情来确保邮件已被发送;这就是last_send_successful的用途。当send子例程成功完成其工作时,它会设置一个内部变量($object->{last_send_successful});这是last_send_successful子检查的内容。除非您试图阻止脚本死亡或引发运行时或语法错误,否则通常不必使用eval块。

您可以将代码简化为以下内容:

$msg->send;

if ($msg->last_send_successful) {
    # woohoo! Message sent
}
else {
    # message did not send.
    # take appropriate action
}

$msg->send;

while (! $msg->last_send_successful) {
    # message did not send.
    # take appropriate action
}