I am trying to send mail using java api.But i am getting exception.Please find the below code.
Expand|Select|Wrap|Line Numbers
- package com;
- import java.util.Properties;
- import javax.mail.Message;
- import javax.mail.MessagingException;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.AddressException;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- import javax.mail.internet.MimeMessage.RecipientType;
- 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", "9000");
- 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);
- System.out.println("Hi");
- }
- catch (MessagingException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public static void main(String[] args)
- {
- SendMail mail = new SendMail("nk.karthick@gmail.com", "karthickrajkumar.n@cognizant.com",
- "TEst", "fsdf");
- mail.send();
- }
- }
javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 9000;
nested exception is:
java.net.ConnectException: Connection refused: connect
at javax.mail.Transport.send0(Transport.java:218)
at javax.mail.Transport.send(Transport.java:80)
at com.SendMail.send(SendMail.java:52)
at com.SendMail.main(SendMail.java:65)