sheepfunk has asked for the wisdom of the Perl Monks concerning the following question:

I'm writing a mailer and want to use the Net::SMTP library, but I want to find a socket with IO::Socket::INET and pass that socket to my $smtp object. Is this possible or recommended? Should I write all the hand shaking stuff using the IO::Socket::INET library instead?

Replies are listed 'Best First'.
Re: Pass a socket to a Net:SMTP object
by pc88mxer (Vicar) on Jun 10, 2008 at 01:01 UTC
    Basically I think bless-ing your socket as a Net::SMTP object will work, but have a look at the Net::SMTP->new method for some additional initialization that goes on.
    use Net::SMTP; # create your own socket however you want my $sock = IO::Socket::INET->new(...); net_smtp_from_existing_socket($sock) or die "couldn't do it, sorry"; sub net_smtp_from_existing_socket { my $sock = shift; my $hello = shift; # the optional hello message bless $sock, 'Net::SMTP'; $sock->autoflush(1); # can set $sock->debug here if you want unless ($sock->response() == CMD_OK) { $sock->close(); return undef; } (${*$sock}{'net_smtp_banner'}) = $sock->message; (${*$sock}{'net_smtp_domain'}) = $sock->message =~ /\A\s*(\S+)/; unless ($sock->hello($hello || "")) { $sock->close(); return undef; } $sock; }
    Alternatively, use Net::SMTP->new to create the socket - the returned object itself is an IO::Socket::INET object.
Re: Pass a socket to a Net:SMTP object
by NetWallah (Canon) on Jun 10, 2008 at 06:33 UTC
    Just a thought ...

    Wouldn't it be cleaner to subclass Net::SMTP, and add the methods you need ?

         "A fanatic is one who redoubles his effort when he has forgotten his aim."—George Santayana

      You guys rock! blessing is the key! So basically I'm testing a socket to see if it's good, and then sending mail if its good like this: my $sock = new IO::Socket::INET->new(PeerPort => 25, PeerAddr => 'PEERADDR', Proto => 'tcp', LocalAddr => 'LOCALADDR' ) or die "Can't bind : $@\n"; $sock->recv($_, 2048); if(/^220/) { print "Connection OK!\n"; bless $sock, 'Net::SMTP'; $smtp = $sock; } else { print "Connection BAD!\n"; exit 1; } $smtp->mail($mail_from); $smtp->recipient($rcpt_to); $smtp->data; $smtp->datasend("From: $from\r\n"); $smtp->datasend("To: $to\r\n"); $smtp->datasend("Subject: $subject\r\n"); $smtp->datasend("\r\n"); $smtp->datasend("$body\r\n"); and so far (as of 5 minutes ago) it seems to be working! If there is something totally wrong with this please let me know, otherwise, thanks so much for the information!