Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to send an email if any error occurs in a Perl script?

Tags:

perl

I am working on a script that does many things, and if at any point during its execution a 'die' gets executed or an error occurs, I'd like to send an email message to myself.

I'm currently using the END block to check the exit status, and if it is greater than 0 call a error email subroutine, but I am wondering if there is a better way. The flaw with this current implementation is that if an error occurs in the email subroutine, an infinite loop will occur.

like image 952
Matthew Avatar asked Dec 05 '25 13:12

Matthew


1 Answers

We've really got two separate questions here:

  1. How do you (reliably) execute code when the program dies without creating an infinite loop if this code also hits a fatal error?

  2. What's the best way to send email from Perl code?

So, to answer each separately:

  1. Rather than an END block, I would use a $SIG{__DIE__} handler (untested code, but should be right):

    $SIG{__DIE__} = \&error_handler;
    
    sub error_handler {
      die @_ if $^S;          # Do nothing if we died in an eval{}
      delete $SIG{__DIE__};   # Clear handler in case following code also dies
    
      print STDERR "Blue Wizard is about to die!\n";
    }
    
  2. There are, of course, many excellent mail-sending modules on CPAN. My personal preference from among them is MIME::Lite, which will send mail using sendmail by default, but, if you're on Windows or some other system with no sendmail command, you can use MIME::Lite->send("smtp"); to send via SMTP directly without going through a local MTA. There is also support for routing mail through an outgoing mail server (handy if your upstream provider blocks port 25!) and handling common authentication methods on that server if needed.

like image 131
Dave Sherohman Avatar answered Dec 08 '25 08:12

Dave Sherohman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!