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

cha*_*mmu 3 email perl 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';
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

Can't locate object method "last_send_successful" via package "MIME::Lite"
Run Code Online (Sandbox Code Playgroud)

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

  1. 所以我错过了什么或者是否可以选择检查上次发送是否成功或者我使用的引用是否不正确?

  2. 这个检查是多余的,因为我已经在使用eval块了吗?

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

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

i a*_*ien 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
}
Run Code Online (Sandbox Code Playgroud)

要么

$msg->send;

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