-
Notifications
You must be signed in to change notification settings - Fork 0
/
pop3client.cc
106 lines (96 loc) · 2.56 KB
/
pop3client.cc
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
#include "Client.h"
#include <cstdlib>
#include <errno.h>
#include <iostream>
#include <string>
#include <climits>
#include <unistd.h>
using namespace std;
/**
* Prints usage of the program
*/
void usage() {
cout << endl << "Usage:" << endl <<
"./pop3client -h hostname [-p port] -u username [-s] [id]" << endl << endl <<
"-h hostname Hostname or host IP address" << endl <<
"-p port TCP port of server (default: 110)" << endl <<
"-u username Username of mail account" << endl <<
"-s Prints short messages without header" << endl <<
"id ID of message which will be retrieved. Without this parameter a list of all messages is printed" << endl;
}
int main(int argc, char *argv[]) {
bool shortMessage=false;
string hostname = "";
string username = "";
unsigned short port = POP3_PORT; // default
// process input arguments
char c;
while ((c = getopt(argc, argv, "h:p:u:s")) != -1) {
switch(c) {
case 'h' : // hostname
hostname = (char *)optarg;
break;
case 'p' : // port
port = strtoul(optarg, (char **)NULL, 10);
if (port == ULONG_MAX && errno == ERANGE) {
cerr << "Port number is incorrect" << endl;
return 1;
}
break;
case 'u':
username = (char *)optarg;
break;
case 's':
shortMessage = true;
break;
default:
// invalid argument
usage();
return 1;
break;
}
}
// check eventual ID of message
unsigned int id = 0; // default value 0 means no ID message
if (argc > optind) { // there are some other parameters yet
// we will process only the first surplus parameter, another parameters will be omitted
// we suppose the next parameter is the id of the message
id = (unsigned int)atoi(argv[optind]);
// according to RFC message ID is counted from 1,
// in case of incorrect conversion id will be 0, which is invalid value then
if (id == 0) {
cerr << "Message ID is in incorrect format" << endl;
return 1;
}
}
// check of mandatory parameters
if (hostname == "" || username == "") {
usage();
return 1;
}
//
// Main part
//
// now we can connect to a POP3 server
try {
Client client(hostname, port);
client.login(username);
client.setShortMessage(shortMessage);
// print message if we have a message ID, otherwise print list of all messages
if (id != 0)
client.getMail(id);
else
client.listMails();
// finish session correctly
client.quit();
}
catch (const char *e) {
cerr << "POP3 client failed: " << e << endl;
return 1;
}
catch (...) {
cerr << "An unknown error occured, quitting..." << endl;
return 1;
}
return 0;
}