Reg : Problem in Sending Mail Through Java Code
bnjutkJun 28 2010 — edited Jun 28 2010Hi All,
I wrote java code to send email to gmail. But am getting the error as following .
Error:
C:\jdevstudio10134\jdk\bin\javaw.exe -client -classpath "C:\jdevstudio10134\jdev\mywork\Prasad\Project1\classes;C:\Program Files\Java\jre1.5.0_14\lib\j2ee.jar" tips.mails.SendMailTest
javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 995
at javax.mail.Transport.send0(Transport.java:218)
at javax.mail.Transport.send(Transport.java:80)
at tips.mails.SendMail.send(SendMail.java:53)
at tips.mails.SendMailTest.main(SendMailTest.java:13)
Process exited with exit code 0.
Class :
--------------
package tips.mails;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
private String from;
private String to;
private String subject;
private String text;
public SendMail(String from, String to, String subject, String text){
this.from = from;
this.to = to;
this.subject = subject;
this.text = text;
}
public void send(){
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "995");
Session mailSession = Session.getDefaultInstance(props);
Message simpleMessage = new MimeMessage(mailSession);
InternetAddress fromAddress = null;
InternetAddress toAddress = null;
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
Transport.send(simpleMessage);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
==============================================================================
Main Class :
package tips.mails;
public class SendMailTest {
public static void main(String[] args) {
String from = "test.d2i3@gmail.com";
String to = "test.d2i3@gmail.com";
String subject = "Hi Rekha";
String message = "A test message";
SendMail sendMail = new SendMail(from, to, subject, message);
sendMail.send();
}
}
========================
Please help me on this .
Thanks in Advance.