我想用 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"
这意味着此方法不存在。但它在我使用的引用文献中给出。
最佳答案
您不需要使用 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
}
关于perl - 如何使用 MIME::Lite perl 检查上次发送的电子邮件是否已成功发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25950164/