I am trying to send a mail through java and it doesn't work. That also doesn't showany error. I am new to javamail so please help:) I searched this question everywhere but I could only find this problem in php. so please let me know how to debug this in java.
public void sendMail(){
String host = "smtp.gmail.com";
String user = "[email protected]";
String password = "pass";
String to = "[email protected]";
String from = "[email protected]";
String subject = "Subject";
String messageText = "Thada ! ";
boolean sessionBug = false;
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable","true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.required","true");
properties.put("mail.smtp.ssl.trust", "smtp.gmail.com");
Session session = Session.getDefaultInstance(properties, null);
session.setDebug(sessionBug);
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
InternetAddress address = new InternetAddress(to);
msg.setRecipient(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
Transport transport = session.getTransport("smtp");
transport.connect(host, user, password);
transport.close();
System.out.println("email sent successfully");
} catch (MessagingException e) {
System.err.println(e);
}
}
I have call the method here
public void sendButtonClicked(ActionEvent actionEvent) {
sendMail();
}
You have to either call send
or sendMessage
to send your email. So your following code
Transport transport = session.getTransport("smtp");
transport.connect(host, user, password);
transport.close();
can be replaced with
Transport.send(msg);
The username and password are already provided through your session properties.