用Perl编写读取POP3邮箱的应用程序

来源: 作者: 2007-10-24 出处:pcdog.com

邮件服务器  
上一页 1 2 

  下面就是它的一个实际例子:

Mail host: pop.mailbox.com
Mailbox username: jane
Mailbox password: secret
Mailbox has 77 message(s).

  当然,仅仅知道消息的数量是远远不够的——你肯定希望知道这些消息的内容。通过Net::POP3的top()方法就能够达到这个目的,它会扫描消息的前X行,并返回一个指向含有已收取数据的数组的参考。下面就是一个例子,(列表B)会取回邮箱里所有消息的前20行:

  列表B

#!/bin/perl
# import package
use Net::POP3;
# ask user for critical variables
print "Mail host: ";
$host = <STDIN>;
chomp($host);
print " ";
print "Mailbox username: ";
$user = <STDIN>;
chomp($user);
print " ";
print "Mailbox password: ";
$pass = <STDIN>;
chomp($pass);
# initiate connection
# default timeout = 120 sec
$conn = Net::POP3->new($host) or die("ERROR: Unable to connect. ");
# login
$numMsg = $conn->login($user, $pass) or die("ERROR: Unable to login. ");
# get message numbers
# iterate over list and print first 20 lines of each
if ($numMsg > 0) {
  $msgList = $conn->list();
  foreach $msg (keys(%$msgList)) {
    $ref = $conn->top($msg, 20);
    print @$ref;
    print " ";
  }
} else {
  print "Mailbox is empty. "; 
}
# close connection
$conn->quit();

  你可以使用get()方法而不用top()方法,从而收取完整的消息。

  如果你希望的话,你可以在命令行通过Getopt::Long模块把服务器的参数传递给程序,下面的列表C显示了这个模块:

  列表C

#!/bin/perl
# import packages
use Net::POP3;
use Getopt::Long;
# read command line options
# display usage message in case of error
GetOptions ('h|host=s' => $host,
      'u|user=s' => $user,
      'p|pass=s' => $pass) or die("Input error. Try calling me with: -h <host> -u <username> -p <password>");
# initiate connection
# default timeout = 120 sec
$conn = Net::POP3->new($host) or die("ERROR: Unable to connect. ");
# login
$numMsg = $conn->login($user, $pass) or die("ERROR: Unable to login. ");
# get message numbers
# iterate over list and print first 20 lines of each
if ($numMsg > 0) {
  $msgList = $conn->list();
  foreach $msg (keys(%$msgList)) {
    $ref = $conn->top($msg, 20);
    print @$ref;
    print " ";
  }
} else {
  print "Mailbox is empty. "; 
}
# close connection
$conn->quit();

  这些代码模板会告诉你如何把Net::POP3集成到需要处理电子邮件的应用程序里。自己动手试试吧,祝你编程愉快!


更多内容请看PCdog.com--POP3协议专题
上一页 1 2 
上一篇:Mailing List (邮件列表)原理简述及我的perl实现
下一篇:用C语言技术进行CGI程序设计