We've all been there - while (1) client process needs to send an email but it fails because it hasn't sent one since yesterday and the server dropped the connection. You don't want to make a new connection every time, so how do you check if your object is still connected? Use the isConnected method of course; oh, except that it doesn't exist... or does it? See below for the undocumented and pseudo-private _NOOP instance method - it is part of the SMTP RFC and thanks to Mr. Barr's attention to detail it is available without having to hack through Net::SMTP's parent classes to issue the command yourself.
#!perl use strict; use warnings; use MIME::Lite; use Net::SMTP; our $smtp; # "self-healing" SMTP connection sub smtp_conn { my $server = shift; if (!defined $smtp or !$smtp->_NOOP) { # there she is ;) $smtp = Net::SMTP->new($server); } return $smtp; } sub send_email { my($server,$from,$to,$subject,$body) = @_; my $smtp = smtp_conn($server) or return; $smtp->mail($from); $smtp->to($to); my $msg = MIME::Lite->new( To => $to, From => $from, Subject => $subject, Data => $body); return $smtp->data($msg->as_string); } while (1) { if ($some_condition eq 'met') { send_email( 'mail.foo.com', 'larryk@foo.com', 'a.wee.moose@bar.com', 'fleeble', 'blaargh'); } sleep 60; }

In reply to Net::SMTP isConnected method by larryk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.