Simple SMTP Client and POP3 Client in Java





5.00/5 (2 votes)
The programs are for sending and receiving emails
Introduction
In this tip, I will show you how to program a simple SMTP client and POP3 client using Java. These programs are used to send and receive to/from an Email Server.
Background
(Optional) These programs are coded according to the Simple Mail Transfer Protocol and Post Office Protocol.
Using the Code
SMTP Client: The function to send Email:
//
public void send(int numOfMails) throws Exception {
String message = "";
System.out.println("Connecting to server ...");
os.writeBytes("HELO\r\n");
int status = 0;//HELO already sent to the server
int count = 0;
while(true){
message = bufReader.readLine();
System.out.println(message);
if(count>=numOfMails)break;
if(message.contains("Aba he")){
System.out.println("Close the connection");
break;
}
System.out.println("Email count: " + count);
switch (status) {
case HELO_RECEIVED: //command HELO already accepted by server
message = bufReader.readLine();
os.writeBytes("MAIL FROM:"+ this.sender + "\r\n");
status = 1;
break;
case MAILFROM_RECEIVED : //command MAIL FROM already accepted by server
os.writeBytes("RCPT TO:"+ this.receiver + "\r\n");
status = 2;
break;
case RCPTTO_RECEIVED : //command RCPT TO already accepted by server
os.writeBytes("DATA\r\n");
status = 3;
break;
case DATA_RECEIVED : //send email body
os.writeBytes(this.body+"\r\n" + "." + "\r\n");
count++;
status=1;
break;
}
}
os.writeBytes("QUIT\r\n");
message = bufReader.readLine();
System.out.println(message);
System.out.println("Client terminates the connection!");
}
Points of Interest
To test the applications, you may download ArgoSoft Mail Server and setup an account. You then connect the Java programs to the Email server by customizing your parameters.
You can use the code to send multiple emails to an email server. This sounds like a flood attack, but you are advised not to do so.
History
- 10th May, 2016: Initial version