1

Possible Duplicate:
How do you send email from a Java app using Gmail?

How do you send mail with java (javax.net, javax.net.ssl, and java.net), without javamail or javaee, to gmail smtp servers? Something starting like this maybe:

            SSLSocketFactory sf = (SSLSocketFactory)SSLSocketFactory.getDefault();
            Socket smtpsocket = sf.createSocket();
         Socket sslsocket = sf.createSocket(smtpsocket,"smtp.gmail.com",465,true);
Community
  • 1
  • 1
Michael Roller
  • 375
  • 2
  • 4
  • 9

2 Answers2

2

You would need to connect to the SMTP port exposed by the gmail server and initiate an SMTP dialogue with the server. This link describes the dialogue: http://slett.net/spam-filtering-for-mx/smtpintro.html. Though this works with plain sockets (without the need for JavaMail package), you need to handle all cases to make it production quality.

Vikdor
  • 23,934
  • 10
  • 61
  • 84
2

You can try this: Good documentation is available here http://www.cs.cf.ac.uk/Dave/PERL/node175.html (I am getting a socket connection error, but the final code would look more or less the same)

public class Mailer {
    private static BufferedReader reader;
    private static OutputStream outputStream;

    public static void main(String args[]) {
        args = new String[]{"smtp.gmail.com","my_id@gmail.com","your_id@gmail.com"};
        try {
            if (args.length == 3) {
                Socket socket = new Socket(args[0], 465);
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                outputStream = socket.getOutputStream();
                smtpCommand("HELO " + args[0]);
                smtpCommand("MAIL From: " + args[1]);
                smtpCommand("RCPT To: " + args[2]);
                smtpCommand("DATA");
                smtpCommand("From: " + args[1] + "\nTo: " + args[2] + "\nContent-Type:text/html;\nSubject: test\n MAIL CONTENT \n.\n");
                System.out.println("\nMessage Sent Successfully to" + args[1].substring(0, args[1].indexOf("@")));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void smtpCommand(String command) throws Exception {
        System.out.println(command);
        reader.readLine();
        outputStream.write((command + "\r\n").getBytes());
    }
}
Vivek
  • 1,316
  • 1
  • 13
  • 23