Perl套接字函数连接到SMTP-Server

时间:2014-05-12 11:53:43

标签: perl sockets network-programming perl5

我只想编写自己的Perl脚本,通过ISP的邮件服务器发送电子邮件。因为我对Perl内置套接字函数很感兴趣,所以我开始尝试它(我已经用IO :: Socket编写了一些小工具,我想提高我对内置函数的了解)。 我目前的代码:

use Socket;
use diagnostics;
my $port = 25;
my $server = "<Servername>";
socket(SOCKET, PF_INET, SOCK_STREAM, getprotobyname("tcp"));
my $inetaddress = inet_aton($server);
my $peeraddress = sockaddr_in($port, $inetaddress);
connect(SOCKET, $peeraddress);
my $answer = <SOCKET>;
#sysread(SOCKET, my $answer, 200);
print "Answer was: ".$answer."\n";
print SOCKET "EHLO <domain>\n";
#syswrite(SOCKET,"EHLO <Domainname>\n", length("EHLO <Domainname>\n"));
$answer = <SOCKET>;
print "Answer was: ".$answer."\n";
close(SOCKET);
#shutdown(SOCKET, 1);

我的问题:我得到了SMTP的第一行(&#34; 220 [...]准备就绪&#34;)。之后它就会停止,好像服务器没有从我那里获得&#34; EHLO&#34; -line。在一定时间之后连接超时,我在屏幕上打印而不是预期的&#34; 250 OK&#34;在我的&#34; EHLO&#34;之后。 评论的行是没有解决问题的尝试。有什么想法吗?

编辑:我知道CPAN上有一些很好的模块,但是它用于学习和娱乐,所以这没有帮助。

1 个答案:

答案 0 :(得分:0)

#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;
use Socket;

my $port = 587;
my $server = "smtp.live.com";
my $inetaddress = inet_aton($server);
my $peeraddress = sockaddr_in($port, $inetaddress);
my $answer;

socket(SOCKET, PF_INET, SOCK_STREAM, getprotobyname("tcp"))
    or die "Can't open socket $!\n";
connect(SOCKET, pack_sockaddr_in($port, $inetaddress))
   or die "Can't connect to port $port!\n";

print SOCKET "EHLO $server\n";

while ($answer = <SOCKET>) {
    print "Answer was: $answer\n";
}

close(SOCKET) or die "Can't close socket: $!";

__OUTPUT__
Answer was: 220 BLU436-SMTP163.smtp.hotmail.com Microsoft ESMTP MAIL Service, Ve
rsion: 8.0.9200.16384 ready at  Sat, 24 May 2014 13:19:57 -0700