junaidp junaidp - 6 months ago 41
Java Question

How to send email in java GWT

I am using this code in my java GWT application

public String greetServer(String input) throws Exception {
try{
Properties props = new Properties();

props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.port", "25");
props.setProperty("mail.host", "smtp.random.com");
props.setProperty("mail.user", "foo@bar.com");
props.setProperty("mail.password", "000000000");

Session mailSession = Session.getDefaultInstance(props, null);
Transport transport = mailSession.getTransport();

MimeMessage message = new MimeMessage(mailSession);
message.setSubject("hello");
message.setContent("helloo sss", "text/plain");
message.addRecipient(Message.RecipientType.TO, new InternetAddress("junaidp@gmail.com"));

transport.connect();
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
} catch(NoSuchProviderException e){
throw new Exception(e);
}

return input;

}


Error: javax.mail.MessagingException: Could not connect to SMTP host: smtp.random.com, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect

if i use

props.setProperty("mail.host", "smtp.live.com");
and use my hotmail account , it gives this error

javax.mail.MessagingException: can't determine local email address


Any idea what could be the solution

thanks

Answer

Here's some Gmail settings which work for me:

//these are fed into the Properties object below:
mail.smtp.starttls.enable = true
mail.transport.protocol   = smtp
mail.smtp.auth            = true

and some Java:

Properties properties = ...

javax.mail.Session session = javax.mail.Session.getInstance(properties, null);
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com", username, password);