File: POP3Client.pm

package info (click to toggle)
libmail-pop3client-perl 2.9-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 88 kB
  • ctags: 42
  • sloc: perl: 517; makefile: 43
file content (1161 lines) | stat: -rw-r--r-- 31,201 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
#******************************************************************************
# $Id: POP3Client.pm,v 2.9 2001/08/18 14:45:24 ssd Exp $
#
# Description:  POP3Client module - acts as interface to POP3 server
# Author:       Sean Dowd <pop3client@dowds.net>
#
# Copyright (c) 1999  Sean Dowd.  All rights reserved.
# This module is free software; you can redistribute it and/or modify
# it under the same terms as Perl itself.
#
#******************************************************************************

package Mail::POP3Client;

use strict;
use Carp;
use IO::Socket;
use Config;

use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);

require Exporter;

@ISA = qw(Exporter);
# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.
@EXPORT = qw(
	
);

my $ID =q( $Id: POP3Client.pm,v 2.9 2001/08/18 14:45:24 ssd Exp $ );
$VERSION = substr q$Revision: 2.9 $, 10;


# Preloaded methods go here.

#******************************************************************************
#* constructor
#* new Mail::POP3Client( USER => user,
#*                       PASSWORD => pass,
#*                       HOST => host,
#*                       AUTH_MODE => [BEST|APOP|PASS],
#*                       TIMEOUT => 30,
#*                       LOCALADDR => 'xxx.xxx.xxx.xxx[:xx]',
#*                       DEBUG => 1 );
#* OR (deprecated)
#* new Mail::POP3Client( user, pass, host [, port, debug, auth_mode, local_addr])
#******************************************************************************
sub new
{
  my $classname = shift;
  my $self = {
	      DEBUG => 0,
	      SERVER => "pop3",
	      PORT => 110,
	      COUNT => -1,
	      SIZE => -1,
	      ADDR => "",
	      STATE => 'DEAD',
	      MESG => 'OK',
	      BANNER => '',
	      MESG_ID => '',
	      AUTH_MODE => 'BEST',
	      EOL => "\015\012",
	      TIMEOUT => 60,
	      STRIPCR => 0,
	      LOCALADDR => undef,
	     };
  $self->{tranlog} = ();
  $Config{osname} =~ /MacOS/i && ($self->{STRIPCR} = 1);
  bless( $self, $classname );
  $self->_init( @_ );

  if ( $self->User() && $self->Pass() )
    {
      $self->Connect();
    }

  return $self;
}



#******************************************************************************
#* initialize - check for old-style params
#******************************************************************************
sub _init {
  my $self = shift;

  # if it looks like a hash
  if ( @_ && (scalar( @_ ) % 2 == 0) )
    {
      # ... and smells like a hash...
      my %hashargs = @_;
      if ( ( defined($hashargs{USER}) &&
	     defined($hashargs{PASSWORD}) ) ||
	   defined($hashargs{HOST})
	 )
	{
	  # ... then it must be a hash!  Push all values into my internal hash.
	  foreach my $key ( keys %hashargs )
	    {
	      $self->{$key} = $hashargs{$key};
	    }
	}
      else {$self->_initOldStyle( @_ );}
    }
  else {$self->_initOldStyle( @_ );}
}

#******************************************************************************
#* initialize using the old positional parameter style new - deprecated
#******************************************************************************
sub _initOldStyle {
  my $self = shift;
  $self->User( shift );
  $self->Pass( shift );
  my $host = shift;
  $host && $self->Host( $host );
  my $port = shift;
  $port && $self->Port( $port );
  my $debug = shift;
  $debug && $self->Debug( $debug );
  my $auth_mode = shift;
  $auth_mode && ($self->{AUTH_MODE} = $auth_mode);
  my $localaddr = shift;
  $localaddr && ($self->{LOCALADDR} = $localaddr);
}

#******************************************************************************
#* What version are we?
#******************************************************************************
sub Version {
  return $VERSION;
}


#******************************************************************************
#* Is the socket alive?
#******************************************************************************
sub Alive
{
  my $me = shift;
  $me->State =~ /^AUTHORIZATION$|^TRANSACTION$/i;
} # end Alive


#******************************************************************************
#* What's the frequency Kenneth?
#******************************************************************************
sub State
{
  my $me = shift;
  my $stat = shift or return $me->{STATE};
  $me->{STATE} = $stat;
} # end Stat


#******************************************************************************
#* Got anything to say?
#******************************************************************************
sub Message
{
  my $me = shift;
  my $msg = shift or return $me->{MESG};
  $me->{MESG} = $msg;
} # end Message


#******************************************************************************
#* set/query debugging
#******************************************************************************
sub Debug
{
  my $me = shift;
  my $debug = shift or return $me->{DEBUG};
  $me->{DEBUG} = $debug;
  
} # end Debug


#******************************************************************************
#* set/query the port number
#******************************************************************************
sub Port
{
  my $me = shift;
  my $port = shift or return $me->{PORT};
  
  $me->{PORT} = $port;

} # end port


#******************************************************************************
#* set the host
#******************************************************************************
sub Host
{
  my $me = shift;
  my $host = shift or return $me->{HOST};

  $me->{INTERNET_ADDR} = inet_aton( $host ) or
    $me->Message( "Could not inet_aton: $host, $!") and return;
  $me->{HOST} = $host;
} # end host

#******************************************************************************
#* set the local address
#******************************************************************************
sub LocalAddr
{
  my $me = shift;
  my $addr = shift or return $me->{LOCALADDR};

  $me->{LOCALADDR} = $addr;
} 


#******************************************************************************
#* query the socket to use as a file handle
#******************************************************************************
sub Socket {
  my $me = shift;
  return $me->{'SOCKET'};
}


#******************************************************************************
#* set/query the USER
#******************************************************************************
sub User
{
  my $me = shift;
  my $user = shift or return $me->{USER};
  $me->{USER} = $user;
  
} # end User


#******************************************************************************
#* set/query the password
#******************************************************************************
sub Pass
{
  my $me = shift;
  my $pass = shift or return $me->{PASSWORD};
  $me->{PASSWORD} = $pass;
  
} # end Pass


#******************************************************************************
#* 
#******************************************************************************
sub Count
{
  my $me = shift;
  my $c = shift;
  if (defined $c and length($c) > 0) {
    $me->{COUNT} = $c;
  } else {
    return $me->{COUNT};
  }
    
} # end Count


#******************************************************************************
#* set/query the size of the mailbox
#******************************************************************************
sub Size
{
  my $me = shift;
  my $c = shift;
  if (defined $c and length($c) > 0) {
    $me->{SIZE} = $c;
  } else {
    return $me->{SIZE};
  }
  
} # end Size


#******************************************************************************
#* 
#******************************************************************************
sub EOL {
  my $me = shift;
  return $me->{'EOL'};
}


#******************************************************************************
#* 
#******************************************************************************
sub Close
{
  my $me = shift;
  if ($me->Alive()) {
    my $s = $me->Socket();
    $me->_sockprint( "QUIT", $me->EOL );

    # from Patrick Bourdon - need this because some servers do not
    # delete in all cases.  RFC says server can respond (in UPDATE
    # state only, otherwise always OK).
    my $line = $me->_sockread();
    
    $me->Message( $line );
    close( $me->Socket() ) or $me->Message("close failed: $!") and return 0;
    $me->State('DEAD');
    $line =~ /^\+OK/i || return 0;
  }
  1;
} # end Close


#******************************************************************************
#* 
#******************************************************************************
sub DESTROY
{
  my $me = shift;
  $me->Close;
} # end DESTROY


#******************************************************************************
#* Connect to the specified POP server
#******************************************************************************
sub Connect
{
  my ($me, $host, $port) = @_;
  
  $host and $me->Host($host);
  $port and $me->Port($port);

  $me->Close();

  my $s = IO::Socket::INET->new( PeerAddr  => $me->Host(),
				 PeerPort  => $me->Port(),
				 Proto     => "tcp",
				 Type      => SOCK_STREAM,
				 LocalAddr => $me->LocalAddr(),
				 Timeout   => $me->{TIMEOUT} )
    or 
      $me->Message( "could not connect socket [$me->{HOST}, $me->{PORT}]: $!" )
	and
	  return 0;
  $me->{SOCKET} = $s;

  $s->autoflush( 1 );
  
  defined(my $msg = $me->_sockread()) or $me->Message("Could not read") and return 0;
  chomp $msg;
  $me->{BANNER}= $msg;

  # add check for servers that return -ERR on connect (not in RFC1939)
  $me->Message($msg);
  $msg =~ /^\+OK/i || return 0;
  
  $me->{MESG_ID}= $1 if ($msg =~ /(<[\w\d\-\.]+\@[\w\d\-\.]+>)/);
  $me->Message($msg);
  
  $me->State('AUTHORIZATION');
  $me->User() and $me->Pass() and $me->Login();
  
} # end Connect


#******************************************************************************
#* login to the POP server.  If the AUTH_MODE is set to BEST, and the server
#* appears to support APOP, it will try APOP, if that fails, then it will try
#* PASS.  If the AUTH_MODE is set to APOP, and the server appears to supports
#* APOP, it will use APOP or it will fail to log in.
#* Otherwise password is sent in clear text.
#******************************************************************************
sub Login
{
  my $me= shift;

  if ($me->{AUTH_MODE} eq 'BEST') {
      if ($me->{MESG_ID}) {
        my $retval = $me->Login_APOP();

        return($retval) if ($me->State eq 'TRANSACTION');
        }
      }
  elsif ($me->{AUTH_MODE} eq 'APOP') {

      return(0) if (!$me->{MESG_ID});   # fail if the server does not support APOP

      return($me->Login_APOP());
      }
  elsif ($me->{AUTH_MODE} ne 'PASS') {
      $me->Message("Programing error. AUTH_MODE (".$me->{AUTH_MODE}.") not BEST | APOP | PASS.");
      return(0);
      }

  return($me->Login_Pass());
}


#******************************************************************************
#* login to the POP server using APOP (md5) authentication.
#******************************************************************************
sub Login_APOP
{
  require MD5;
  
  my $me = shift;
  my $s = $me->Socket();
  my $hash= MD5->hexhash ($me->{MESG_ID} . $me->Pass);
  
  $me->_sockprint( "APOP " , $me->User , ' ', $hash, $me->EOL );
  my $line = $me->_sockread();
  chomp $line;
  $me->Message($line);
  $line =~ /^\+OK/ or $me->Message("APOP failed: $line") and $me->State('AUTHORIZATION')
    and return 0;
  $me->State('TRANSACTION');
  
  $me->POPStat() or return 0;
}


#******************************************************************************
#* login to the POP server using simple (cleartext) authentication.
#******************************************************************************
sub Login_Pass
{
  my $me = shift;
  my $s = $me->Socket();
  $me->_sockprint( "USER " , $me->User() , $me->EOL );
  my $line = $me->_sockread();
  chomp $line;
  $me->Message($line);
  $line =~ /^\+/ or $me->Message("USER failed: $line") and $me->State('AUTHORIZATION')
    and return 0;
  
  $me->_sockprint( "PASS " , $me->Pass() , $me->EOL );
  $line = $me->_sockread();
  chomp $line;
  $me->Message($line);
  $line =~ /^\+OK/ or $me->Message("PASS failed: $line") and $me->State('AUTHORIZATION')
    and return 0;
  
  $me->State('TRANSACTION');

  $me->POPStat() or return 0;
  
} # end Login


#******************************************************************************
#* Get the Head of a message number.  If you give an optional number
#* of lines you will get the first n lines of the body also.  This
#* allows you to preview a message.
#******************************************************************************
sub Head
{
  my $me = shift;
  my $num = shift;
  my $lines = shift;
  $lines ||= 0;
  $lines =~ /\d+/ || ($lines = 0);
  my $header = '';
  my $s = $me->Socket();
  
  $me->_sockprint( "TOP $num $lines", $me->EOL );
  my $line = $me->_sockread();
  chomp $line;
  $line =~ /^\+OK/ or $me->Message("Bad return from TOP: $line") and return;
  $line =~ /^\+OK (\d+) / and my $buflen = $1;
  
  while (1) {
    $line = $me->_sockread();
    last if $line =~ /^\.\s*$/;
    $line =~ s/^\.\././;
    $header .= $line;
  }
  
  return wantarray ? split(/\r?\n/, $header) : $header;
} # end Head


#******************************************************************************
#* Get the header and body of a message
#******************************************************************************
sub HeadAndBody
{
  my $me = shift;
  my $num = shift;
  my $mandb = '';
  my $s = $me->Socket();
  
  $me->_sockprint( "RETR $num", $me->EOL );
  my $line = $me->_sockread();
  chomp $line;
  $line =~ /^\+OK/ or $me->Message("Bad return from RETR: $line") and return;
  $line =~ /^\+OK (\d+) / and my $buflen = $1;
  
  while (1) {
    $line = $me->_sockread();
    last if $line =~ /^\.\s*$/;
    # convert any '..' at the start of a line to '.'  
    $line =~ s/^\.\././;  
    $mandb .= $line;  
  } 
  
  return wantarray ? split(/\r?\n/, $mandb) : $mandb;
  
} # end HeadAndBody


#******************************************************************************
#* get the head and body of a message and write it to a file handle.
#* Sends the raw data: does no CR/NL stripping or mapping.
#******************************************************************************
sub HeadAndBodyToFile
{
  my $me = shift;
  my $fh = shift;
  my $num = shift;
  my $body = '';
  my $s = $me->Socket();
  
  $me->_sockprint( "RETR $num", $me->EOL );
  my $line = $me->_sockread();
  chomp $line;
  $line =~ /^\+OK/ or $me->Message("Bad return from RETR: $line") and return 0;
  $line =~ /^\+OK (\d+) / and my $buflen = $1;
  
  while (1) {
    $line = $me->_sockread();
    last if $line =~ /^\.\s*$/;
    # convert any '..' at the start of a line to '.'  
    $line =~ s/^\.\././;
    print $fh $line;
  }
  return 1;
} # end BodyToFile



#******************************************************************************
#* get the body of a message
#******************************************************************************
sub Body
{
  my $me = shift;
  my $num = shift;
  my $body = '';
  my $s = $me->Socket();
  
  $me->_sockprint( "RETR $num", $me->EOL );
  my $line = $me->_sockread();
  chomp $line;
  $line =~ /^\+OK/ or $me->Message("Bad return from RETR: $line") and return;
  $line =~ /^\+OK (\d+) / and my $buflen = $1;
  
  # skip the header
  do {
    $line = $me->_sockread();
  } until $line =~ /^\s*$/;
  
  while (1) {
    $line = $me->_sockread();
    last if $line =~ /^\.\s*$/;
    # convert any '..' at the start of a line to '.'  
    $line =~ s/^\.\././;  
    $body .= $line;  
  } 
  
  return wantarray ? split(/\r?\n/, $body) : $body;
  
} # end Body


#******************************************************************************
#* get the body of a message and write it to a file handle.  Sends the raw data:
#* does no CR/NL stripping or mapping.
#******************************************************************************
sub BodyToFile
{
  my $me = shift;
  my $fh = shift;
  my $num = shift;
  my $body = '';
  my $s = $me->Socket();
  
  $me->_sockprint( "RETR $num", $me->EOL );
  my $line = $me->_sockread();
  chomp $line;
  $line =~ /^\+OK/ or $me->Message("Bad return from RETR: $line") and return;
  $line =~ /^\+OK (\d+) / and my $buflen = $1;
  
  # skip the header
  do {
    $line = $me->_sockread();
  } until $line =~ /^\s*$/;
  
  while (1) {
    $line = $me->_sockread();
    chomp $line;
    last if $line =~ /^\.\s*$/;
    # convert any '..' at the start of a line to '.'  
    $line =~ s/^\.\././;
    print $fh $line, "\n";
  } 
} # end BodyToFile



#******************************************************************************
#* handle a STAT command - returns the number of messages in the box
#******************************************************************************
sub POPStat {
  my $me = shift;
  my $s = $me->Socket();
  
  $me->_sockprint( "STAT", $me->EOL );
  my $line = $me->_sockread();
  $line =~ /^\+OK/ or $me->Message("STAT failed: $line") and return -1;
  $line =~ /^\+OK (\d+) (\d+)/ and $me->Count($1), $me->Size($2);
  
  return $me->Count();
}


#******************************************************************************
#* issue the LIST command
#******************************************************************************
sub List {
  my $me = shift;
  my $num = shift || '';
  my $CMD = shift || 'LIST';
  $CMD=~ tr/a-z/A-Z/;
  
  my $s = $me->Socket();
  $me->Alive() or return;
  
  my @retarray = ();
  my $ret = '';

  # apparently there is a server that cannot handle 'LIST '.
  if ( $num )
    {
      $me->_sockprint( "$CMD $num", $me->EOL );
    }
  else
    {
      $me->_sockprint( "$CMD", $me->EOL );
    }
  my $line = $me->_sockread();
  $line =~ /^\+OK/ or $me->Message("$line") and return;
  if ($num) {
    $line =~ s/^\+OK\s*//;
    return $line;
  }
  while( defined( $line = $me->_sockread() ) ) {
    $line =~ /^\.\s*$/ and last;
    $ret .= $line;
    chomp $line;
    push(@retarray, $line);
  }
  if ($ret) {
    return wantarray ? @retarray : $ret;
  }
}

#******************************************************************************
#* issue the LIST command, but return results in an indexed array.
#******************************************************************************
sub ListArray {
  my $me = shift;
  my $num = shift || '';
  my $CMD = shift || 'LIST';
  $CMD=~ tr/a-z/A-Z/;
  
  my $s = $me->Socket();
  $me->Alive() or return;
  
  my @retarray = ();
  my $ret = '';
  
  $me->_sockprint( "$CMD $num", $me->EOL );
  my $line = $me->_sockread();
  $line =~ /^\+OK/ or $me->Message("$line") and return;
  if ($num) {
    $line =~ s/^\+OK\s*//;
    return $line;
  }
  while( defined( $line = $me->_sockread() ) ) {
    $line =~ /^\.\s*$/ and last;
    $ret .= $line;
    chomp $line;
    my ($num, $uidl) = split ' ', $line;
    $retarray[$num] = $uidl;
  }
  if ($ret) {
    return wantarray ? @retarray : $ret;
  }
}


#******************************************************************************
#* retrieve the given message number - uses HeadAndBody
#******************************************************************************
sub Retrieve {
  return HeadAndBody( @_ );
}

#******************************************************************************
#* retrieve the given message number to the given file handle- uses
#* HeadAndBodyToFile
#******************************************************************************
sub RetrieveToFile {
  return HeadAndBodyToFile( @_ );
}


#******************************************************************************
#* implement the LAST command - see the rfc (1081) OBSOLETED by RFC
#******************************************************************************
sub Last {
  my $me = shift;
  
  my $s = $me->Socket();
  
  $me->_sockprint( "LAST", $me->EOL );
  my $line = $me->_sockread();
  
  $line =~ /\+OK (\d+)\D*$/ and return $1;
}


#******************************************************************************
#* reset the deletion stat
#******************************************************************************
sub Reset {
  my $me = shift;
  
  my $s = $me->Socket();
  $me->_sockprint( "RSET", $me->EOL );
  my $line = $me->_sockread();
  $line =~ /^\+OK/ and return 1;
  return 0;
}


#******************************************************************************
#* delete the given message number
#******************************************************************************
sub Delete {
  my $me = shift;
  my $num = shift || return;
  
  my $s = $me->Socket();
  $me->_sockprint( "DELE $num",  $me->EOL );
  my $line = $me->_sockread();
  $me->Message($line);
  $line =~ /^\+OK/ && return 1;
  return 0;
}


#******************************************************************************
#* UIDL - submitted by Dion Almaer (dion@member.com)
#******************************************************************************
sub Uidl {
  my $me = shift;
  my $num = shift || '';
  
  my $s = $me->Socket();
  $me->Alive() or return;
  
  my @retarray = ();
  my $ret = '';
  
  $me->_sockprint( "UIDL $num", $me->EOL );
  my $line = $me->_sockread();
  $line =~ /^\+OK/ or $me->Message($line) and return;
  if ($num) {
    $line =~ s/^\+OK\s*//;
    return $line;
  }
  while( defined( $line = $me->_sockread() ) ) {
    $line =~ /^\.\s*$/ and last;
    $ret .= $line;
    chomp $line;
    my ($num, $uidl) = split ' ', $line;
    $retarray[$num] = $uidl;
  }
  if ($ret) {
    return wantarray ? @retarray : $ret;
  }
}



#*****************************************************************************
#* funnel all read/write through here to allow easier debugging
#* (mitra@earth.path.net)
#*****************************************************************************
sub _sockprint
{
  my $me = shift;
  my $s = $me->Socket();
  $me->Debug and carp "POP3 -> ", @_;
  my $outline = "@_";
  chomp $outline;
  push(@{$me->{tranlog}}, $outline);
  print $s @_;
}

sub _sockread
{
  my $me = shift;
  my $line = $me->Socket()->getline();

  # Macs seem to leave CR's or LF's sitting on the socket.  This
  # removes them.
  $me->{STRIPCR} && ($line =~ s/^[\r]+//);
  
  $me->Debug and carp "POP3 <- ", $line;
  $line =~ /^[\\+\\-](OK|ERR)/i && do {
    my $l = $line;
    chomp $l;
    push(@{$me->{tranlog}}, $l);
  };
  return $line;
}


# end package Mail::POP3Client

# Autoload methods go after =cut, and are processed by the autosplit program.

1;
__END__



################################################################################
# POD Documentation (perldoc Mail::POP3Client or pod2html this_file)
################################################################################

=head1 NAME

Mail::POP3Client - Perl 5 module to talk to a POP3 (RFC1939) server

=head1 SYNOPSIS

  use Mail::POP3Client;
  $pop = new Mail::POP3Client( USER     => "me",
			       PASSWORD => "mypassword",
			       HOST     => "pop3.do.main" );
  for( $i = 1; $i <= $pop->Count(); $i++ ) {
    foreach( $pop->Head( $i ) ) {
      /^(From|Subject):\s+/i && print $_, "\n";
    }
  }
  $pop->Close();
  # OR
  $pop2 = new Mail::POP3Client( HOST  => "pop3.otherdo.main" );
  $pop2->User( "somebody" );
  $pop2->Pass( "doublesecret" );
  $pop2->Connect() || die $pop2->Message();
  $pop2->Close();

=head1 DESCRIPTION

This module implements an Object-Oriented interface to a POP3 server.
It implements RFC1939 (http://www.faqs.org/rfcs/rfc1939.html)

=head1 EXAMPLES

Here is a simple example to list out the From: and Subject: headers in
your remote mailbox:

  #!/usr/local/bin/perl
  
  use Mail::POP3Client;
  
  $pop = new Mail::POP3Client( USER     => "me",
			       PASSWORD => "mypassword",
			       HOST     => "pop3.do.main" );
  for ($i = 1; $i <= $pop->Count(); $i++) {
    foreach ( $pop->Head( $i ) ) {
      /^(From|Subject):\s+/i and print $_, "\n";
    }
    print "\n";
  }

=head1 CONSTRUCTORS

Old style (deprecated):
   new Mail::POP3Client( USER, PASSWORD [, HOST, PORT, DEBUG, AUTH_MODE] );

New style (shown with defaults):
   new Mail::POP3Client( USER      => "",
                         PASSWORD  => "",
                         HOST      => "pop3",
                         PORT      => 110,
                         AUTH_MODE => 'BEST',
                         DEBUG     => 0,
                         TIMEOUT   => 60,
                         LOCALADDR => 'xxx.xxx.xxx.xxx[:xx]',
                       );

=over 4

=item *
USER is the userID of the account on the POP server

=item *
PASSWORD is the cleartext password for the userID

=item *
HOST is the POP server name or IP address (default = 'pop3')

=item *
PORT is the POP server port (default = 110)

=item *
DEBUG - any non-null, non-zero value turns on debugging (default = 0)

=item *
AUTH_MODE - pass 'APOP' to force APOP (MD5) authorization. (default is 'BEST')

=item *
TIMEOUT - set a timeout value for socket operations (default = 60)

=item *
LOCALADDR - allow selecting a local inet address to use

=back

=head1 METHODS

These commands are intended to make writing a POP3 client easier.
They do not necessarily map directly to POP3 commands defined in
RFC1081 or RFC1939, although all commands should be supported.  Some
commands return multiple lines as an array in an array context.

=over 8

=item I<new>( USER => 'user', PASSWORD => 'password', HOST => 'host',
              PORT => 110, DEBUG => 0, AUTH_MODE => 'BEST', TIMEOUT => 60 )

Construct a new POP3 connection with this.  You should use the
hash-style constructor.  B<The old positional constructor is
deprecated and will be removed in a future release.  It is strongly
recommended that you convert your code to the new version.>

You should give it at least 2 arguments: USER and PASSWORD.  The
default HOST is 'pop3' which may or may not work for you.  You can
specify a different PORT (be careful here).

new will attempt to Connect to and Login to the POP3 server if you
supply a USER and PASSWORD.  If you do not supply them in the
constructor, you will need to call Connect yourself.

The valid values for AUTH_MODE are 'BEST', 'PASS' and 'APOP'.  BEST
says to try APOP if the server appears to support it and it can be
used to successfully log on, otherwise revert to PASS.  APOP implies
that an MD5 checksum will be used instead of sending your password in
cleartext.  However, B<if the server does not claim to support APOP,
the cleartext method will be used.  Be careful.> There are a few
servers that will send a timestamp in the banner greeting, but APOP
will not work with them (for instance if the server does not know your
password in cleartext).  If you think your authentication information
is correct, run in DEBUG mode and look for errors regarding
authorization.  If so, then you may have to use 'PASS' for that server.

If you enable debugging with DEBUG => 1, socket traffic will be echoed
to STDERR.

Another warning, it's impossible to differentiate between a timeout
and a failure.


=item I<Head>( MESSAGE_NUMBER [, PREVIEW_LINES ] )

Get the headers of the specified message, either as an array or as a
string, depending on context.

You can also specify a number of preview lines which will be returned
with the headers.  This may not be supported by all POP3 server
implementations as it is marked as optional in the RFC.  Submitted by
Dennis Moroney <dennis@hub.iwl.net>.

=item I<Body>( MESSAGE_NUMBER )

Get the body of the specified message, either as an array of lines or
as a string, depending on context.

=item I<BodyToFile>( FILE_HANDLE, MESSAGE_NUMBER )

Get the body of the specified message and write it to the given file handle.
my $fh = new IO::Handle();
$fh->fdopen( fileno( STDOUT ), "w" );
$pop->BodyToFile( $fh, 1 );

Does no stripping of NL or CR.


=item I<HeadAndBody>( MESSAGE_NUMBER )

Get the head and body of the specified message, either as an array of
lines or as a string, depending on context.

=over 4

=item Example

foreach ( $pop->HeadAndBody( 1 ) )
   print $_, "\n";

prints out the complete text of message 1.

=back

=item I<HeadAndBodyToFile>( FILE_HANDLE, MESSAGE_NUMBER )

Get the head and body of the specified message and write it to the given file handle.
my $fh = new IO::Handle();
$fh->fdopen( fileno( STDOUT ), "w" );
$pop->HeadAndBodyToFile( $fh, 1 );

Does no stripping of NL or CR.


=item I<Retrieve>( MESSAGE_NUMBER )

Same as HeadAndBody.

=item I<RetrieveToFile>( FILE_HANDLE, MESSAGE_NUMBER )

Same as HeadAndBodyToFile.

=item I<Delete>( MESSAGE_NUMBER )

Mark the specified message number as DELETED.  Becomes effective upon
QUIT.  Can be reset with a Reset message.

=item I<Connect>

Start the connection to the POP3 server.  You can pass in the host and
port.

=item I<Close>

Close the connection gracefully.  POP3 says this will perform any
pending deletes on the server.

=item I<Alive>

Return true or false on whether the connection is active.

=item I<Socket>

Return the file descriptor for the socket.

=item I<Size>

Set/Return the size of the remote mailbox.  Set by POPStat.

=item I<Count>

Set/Return the number of remote messages.  Set during Login.

=item I<Message>

The last status message received from the server or a message
describing any problem encountered.

=item I<State>

The internal state of the connection: DEAD, AUTHORIZATION, TRANSACTION.

=item I<POPStat>

Return the results of a POP3 STAT command.  Sets the size of the
mailbox.

=item I<List>([message_number])

Returns the size of the given message number when called with an
argument using the following format:

   <message_number> <size_in_bytes>

If message_number is omitted, List behaves the same as ListArray,
returning an indexed array of the sizes of each message in the same
format.

You can parse the size in bytes using split:
 ($msgnum, $size) = split ' ', $pop -> List( n )


=item I<ListArray>

Return a list of sizes of each message.  This returns an indexed
array, with each message number as an index (starting from 1) and the
value as the next entry on the line.  Beware that some servers send
additional info for each message for the list command.  That info may
be lost.

=item I<Uidl>( [MESSAGE_NUMBER] )

Return the unique ID for the given message (or all of them).  Returns
an indexed array with an entry for each valid message number.
Indexing begins at 1 to coincide with the server's indexing.

=item I<Last>

Return the number of the last message, retrieved from the server.

=item I<Reset>

Tell the server to unmark any message marked for deletion.

=item I<User>( [USER_NAME] )

Set/Return the current user name.

=item I<Pass>( [PASSWORD] )

Set/Return the current user name.

=item I<Login>

Attempt to login to the server connection.

=item I<Host>( [HOSTNAME] )

Set/Return the current host.

=item I<Port>( [PORT_NUMBER] )

Set/Return the current port number.

=back

=head1 AUTHOR

Sean Dowd <pop3client@dowds.net>

=head1 CREDITS

Based loosely on News::NNTPClient by Rodger Anderson
<rodger@boi.hp.com>.

=head1 SEE ALSO

perl(1).

=cut