Wednesday, December 08, 2004

Cheap and nasty java smtp client

This is for those situations where you want to send a short, plain-text email, and mail.jar and its associated dependencies are not available.

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

/**
 * A very, very basic SMTP client for sending one-liner emails.
 * Doesn't support authentication or anything else fancy. Use
 * only when your desire to not have to depend on mail.jar outweighs
 * the importance of the email ever actually getting there.
 *
 * @author  jeff_robertson@yahoo.com
 */
public class StoopidSmtpSender {
    
    private String host;
    private int port;
    private PrintStream logStream;
    
    public StoopidSmtpSender(String host, int port, PrintStream logStream) {
        this.host=host;
        this.port=port;
        this.logStream = logStream;
    }
        
    public StoopidSmtpSender(String host) {
        this.host=host;
        this.port=25;
    }

    public void send(String from, String to, String subject, String body) throws java.io.IOException {
        Socket s = new Socket(host, port);

        PrintStream ps;
        
        if( logStream == null)
           ps = new PrintStream(s.getOutputStream());
        else 
           ps = new PrintStream(s.getOutputStream()) {
                public void println(String str) {
                    logStream.println(str);
                    super.println(str);
                }
           };
           
        BufferedReader br;
        
        if( logStream == null)
            br = new BufferedReader( new InputStreamReader(s.getInputStream()));
        else
            br = new BufferedReader( new InputStreamReader(s.getInputStream())) {
                public String readLine() throws IOException {
                    String str = super.readLine();
                    logStream.println(str);
                    return str;
                }
            };


        br.readLine(); // read and throw away intial message    

        ps.println("HELO");
        br.readLine();    
        
        ps.println("mail from: <" + from + ">");
        br.readLine();    
        
        ps.println("rcpt to: <" + to + ">");
        br.readLine();    
        
        ps.println("data");
        br.readLine();    
        
        ps.println("Subject: " + subject);
        ps.println();
        ps.println(body);
        ps.println(".");
        
        br.readLine();    
        
        ps.close();
        s.close();
    }
}

Comments: