2013-03-15 62 views
0

以下是我对在Perl发送HTML电子邮件的代码如何得到响应(成功或失败),而在Perl发送HTML邮件

use strict; 
use warnings; 

use Email::Sender::Simple qw(sendmail); 
use Email::Sender::Transport::SMTP(); 
use Email::Simple(); 
use Email::Simple::Creator(); 
use Email::MIME::CreateHTML; 


my $smtpserver = 'xxx.xxx.xx'; 
my $smtpport = 25; 
my $smtpuser = '[email protected]'; 
my $smtppassword = 'xxxx'; 

my $transport = Email::Sender::Transport::SMTP->new({ 
    host => $smtpserver, 
    port => $smtpport, 
    sasl_username => $smtpuser, 
    sasl_password => $smtppassword, 
}); 


my $html ="<div>Success</div>"; 
my $plain_text ="plain text"; 

my $email = Email::MIME->create_html(
     header => [ 
       From => '[email protected]', 
       To => '[email protected]', 
       Subject => 'Test Mail', 
     ], 
     body => $html, 
     text_body => $plain_text 
); 

sendmail($email, { transport => $transport }); 

其工作fine.Now我需要找到的响应邮件发送。

为我修改了代码为

eval { 
sendmail($email, { transport => $transport }); # this is try catch method 
}; 
if ([email protected]) { 
     # where [email protected] is a object of Email::Sender::Failure 
    print [email protected]>message; 
    print"\n"[email protected]>code ; 

}else{ 
print "success"; 
} 

现在让我知道,有没有更好的方式来实现这一目标?

回答

0

两件事情可以改善你的代码。

首先,尽可能快地采取[email protected]的副本(如果您在处理错误时做了某些操作,则会更改[email protected]的值)。

if (my $e = [email protected]) { 
    print $e->message; 
    print"\n" . $e->code; 
} 

其次,这也是值得考虑像Try::Tiny一个模块,这将使你的异常处理代码看上去有点更好。

try { 
    sendmail($email, { transport => $transport }); 
} catch { 
    # Exception is in $_ 
    print $_->message; 
    print"\n" . $_->code; 
}