I have tried to write a code to send email using Java. But this code is not working. When the code is executed it gets stuck at transport.send(message). It's stuck there forever. Also I am not sure if the rest of the code is correct or not.
//first from, to, subject, & text values are set
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;
}
//send method is called in the end
public void send(){
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
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); // this is where code hangs
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Then give a try, if you succeed, investigate further to find the culprit.
In my case it was the Antivirus, and I had to make an exception for outbound mails on
SMTP
to send the mail successfully.Replace Session.getDefaultInstance with Session.getInstance.
If that doesn't solve the problem, read the JavaMail FAQ, which has debugging tips.
Had this exact same problem. You have to close the transport in the catch block. The reason the code freezes is because the smtp server connection never gets shut down on the client side unless you do it manually.
But the most efficient way to make sure javamail exits correctly is to bundle the javamail logic into one try block and close the transport in a finally block. Try this. [EDIT] After being alerted that the above code didn't work here is the code that compiles correctly.
When you Declare
Transport.send()
it will not work use this instead oftransport.sendMessage(message, message.getAllRecipients());
and also declare ajavax.mail.Transport transport = session.getTransport("smtp");
object as shown in the code.then the following code will appear like this Thank you, hope this will work perfectly
Please try this,
I had the exact same issue. I took me multiple hours to find the source of the problem. I was using the wrong dependency / dependency combination...
Changing it to ...
... solved the issue.