POP3(Post Office Protocol Version 3)协议用于接收电子邮件。实现POP3协议主要包含:
- 连接POP3服务器:默认端口110或995(用于SSL连接)。
- 鉴权:使用用户名和密码登录。
- 获取邮件列表:使用LIST或者UIDL命令获取邮件ID和大小。
- 获取邮件内容:使用RETR命令下载邮件内容。
- 标记或删除邮件:使用DELE命令标记删除或删除邮件。
- 断开连接:使用QUIT命令断开连接。
实现一个简单的POP3客户端可以如下:
public class POP3Client {
private Socket socket;
private OutputStream out;
private String server;
private int port = 110;
public POP3Client(String server, int port) throws IOException {
this.server = server;
this.port = port;
connect();
}
private void connect() throws IOException {
socket = new Socket(server, port);
out = socket.getOutputStream();
BufferedReader in =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
String welcomeMsg = in.readLine(); // +OK
sendCommand("USER username"); // +OK
sendCommand("PASS password"); // +OK
}
private void sendCommand(String cmd) throws IOException {
out.write((cmd + "\r\n").getBytes());
String response = socket.getInputStream().readLine();
}
public List<Mail> getMails() throws IOException {
sendCommand("LIST"); // +OK
String response;
List<Mail> mails = new ArrayList<>();
while ((response = socket.getInputStream().readLine()) != null) {
if (response.equals(".")) break; // End of response
String[] tokens = response.split(" ");
Mail mail = new Mail(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]));
mails.add(mail);
}
return mails;
}
public Mail getMail(int id) throws IOException {
sendCommand("RETR " + id); // +OK
StringBuilder content = new StringBuilder();
String line;
while ((line = socket.getInputStream().readLine()) != null) {
if (line.equals(".")) break;
content.append(line + "\n");
}
return new Mail(id, content.toString());
}
// 其他命令...
}
我们可以这样使用POP3Client接收邮件:
POP3Client client = new POP3Client("pop.example.com");
List<Mail> mails = client.getMails();
for (Mail mail : mails) {
Mail content = client.getMail(mail.getId());
System.out.println(content.getContent());
}