Sending an email with the SMTP protocol in Java

The optional package JavaMail allows you to do this. I’ve devoted a separate category that tells you where you can d/l it plus some tutorials and links.

This following class doesn’t use JavaMail, but it uses SMTP commands to allow to send a simple mail. To run it, you need to specify an SMTP server, a from and to email address, subject and body.

SMTPEmail.java:

import java.io.*;
import java.net.*;

public class SMTPEmail
{
    private Socket smtpSocket;
    private BufferedReader br;
    private BufferedWriter bw;
       
    private String smtpHost;
    
    public SMTPEmail(String smtpHost) throws IOException {
        this.smtpHost = smtpHost;
    }
    
    public void connect() throws IOException {
        smtpSocket = new Socket(smtpHost, 25);
        br = new BufferedReader(new InputStreamReader(smtpSocket.getInputStream()));
        bw = new BufferedWriter(new OutputStreamWriter(smtpSocket.getOutputStream()));
    }
    
    private void disconnect() throws IOException {
        smtpSocket.close();
    }
    
    private void send(String str) throws IOException {
        System.out.println("Sending: " + str);
        bw.write(str + "rn");
        bw.flush();
    }
    
    private String receive() throws IOException {
        String str = br.readLine();
        System.out.println("Receiving: " + str);
        return str;
    }
    
    public void sendMail(String fromAddress, String toAddress, 
                         String subject, String body) throws IOException {
        connect();
        String whoami = InetAddress.getLocalHost().getHostName();
        send("HELO " + whoami);
        receive();
        send("MAIL FROM: <" + fromAddress + "> ");
        receive();
        send("RCPT TO: <" + toAddress + "> ");
        receive();
        send("DATA");
        receive();
        send("TO: " + toAddress);
        send("FROM: " + fromAddress);
        send("SUBJECT: " + subject + "rn");
        send(body);
        send("rn.rn");
        receive();
        send("QUIT");
        disconnect();
    }
}

Main.java:

import java.io.*; 
 
public class Main { 
   public static void main(String[] args) { 
      if (args.length != 5) { 
         System.err.println("usage: java Main " + " "); 
         System.exit(1); 
      } 
 
      try { 
         SMTPEmail smtp = new SMTPEmail(args[0]); 
         smtp.sendMail(args[1], args[2], args[3], args[4]); 
      } catch(IOException e) { 
         e.printStackTrace(); 
      } 
   } 
}