Can anybody help on sending mail through Java Code

I am trying to send the mail using the java code and I am unable to do it. My code is
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
public class EmailExample {
public static void main(String[] args)
Socket smtpSocket;
DataOutputStream os;
BufferedReader is;
Date dDate = new Date();
DateFormat dFormat = DateFormat.getDateInstance(DateFormat.FULL,Locale.US);
try
smtpSocket = new Socket("www.gmail.com",80);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new BufferedReader(new InputStreamReader(smtpSocket.getInputStream()));
System.out.println("Hi How is this?");
os.writeBytes("HELLO\r\n");
// You will add the email address that the server
// you are using know you as.
os.writeBytes("MAIL From: <[email protected]>\r\n");
// Who the email is going to.
os.writeBytes("RCPT To: <[email protected]>\r\n");
//IF you want to send a CC then you will have to add this
//os.writeBytes("RCPT Cc: <[email protected]>\r\n");
// Now we are ready to add the message and the
// header of the email to be sent out.
os.writeBytes("DATA\r\n");
os.writeBytes("X-Mailer: Via Java\r\n");
os.writeBytes("DATE: " + dFormat.format(dDate) + "\r\n");
System.out.println("DATE: " + dFormat.format(dDate) + "\r\n");
os.writeBytes("From: Me <[email protected]>\r\n");
os.writeBytes("To: YOU <[email protected]>\r\n");
//Again if you want to send a CC then add this.
//os.writeBytes("Cc: CCDUDE <[email protected]>\r\n");
//Here you can now add a BCC to the message as well
//os.writeBytes("RCPT Bcc: BCCDude<[email protected]>\r\n");
String sMessage = "Your subjectline here";
os.writeBytes("Subject: Your subjectline here\r\n");
os.writeBytes(sMessage + "\r\n");
os.writeBytes("\r\n.\r\n");
os.writeBytes("QUIT\r\n");
// Now send the email off and check the server reply.
// Was an OK is reached you are complete.
String responseline;
while((responseline = is.readLine())!=null)
{   System.out.println(responseline);
if(responseline.indexOf("Ok") != -1)
break;
} catch (IOException e) {
e.printStackTrace();
It is compiling and runnung properly. Please Help me on this.
Thanks.
Satya.
Advertisement
Reply

You're mishandling the responses. You terminate if you don't get an "Ok" string, but that's not how success is defined - you should get a 200 code back, typically with an "OK" (not caps) message.
It doesn't help that you're ignoring all of the server output after each command, so you never find out if anything goes wrong.
You're also reinventing a wheel. The JavaMail API exists for this: http://java.sun.com/products/javamail/