Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Net::SMTP isConnected method

by larryk (Friar)
on Jan 22, 2004 at 11:18 UTC ( #323149=snippet: print w/ replies, xml ) Need Help??

Description: 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;
}
Comment on Net::SMTP isConnected method
Download Code

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://323149]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2015-08-01 03:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (285 votes), past polls