Nasser Nasser - 2 months ago 21
Java Question

Can't Send Email using SMTP in JavaFX

When I press a button to send an Email in JavaFx it opens an QuantumToolKit.class tab and the application hangs on
The button works fine with other functionality

SMTP code

package application;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.JOptionPane;

public class EmailController {
String reciever;
String subj;
String con;
final String username;
final String password;
String from;
String host;
String put_auth;
String put_ttls;
String put_host;
String put_port;
public EmailController (){
username="username";
password="passwrd";
from="example";
host="smtp.gmail.com";
reciever="reciever_example";
subj="Subject";
con="Content";
put_auth="mail.smtp.auth";
put_ttls="mail.smtp.strarttls.enable";
put_host="mail.smtp.host";
put_port="mail.smtp.port";
}
public void send()
{

Properties props=new Properties();
props.put(put_auth, "true");
props.put(put_ttls, "true");
props.put(put_host, host);
props.put(put_port, "587");

Session session=Session.getInstance(props,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication () {
return new PasswordAuthentication(username,password);
}
});
try {
Message message=new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(reciever));
message.setSubject(subj);
message.setText(con);
Transport.send(message);
JOptionPane.showMessageDialog(null, "Done");
}catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}


The #onAction function in controller class code

public void send_Email(){
sendm.send(); //sendm is an object from class EmailController
}


FXML code for this button only

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane prefHeight="557.0" prefWidth="604.0" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Heart">
<children>
<Button layoutX="88.0" layoutY="307.0" mnemonicParsing="false" onAction="#send_Email" prefHeight="26.0" prefWidth="356.0" text="Send email" />
</children>
</AnchorPane>

Answer

I have fixed it , I just wrote starttls wrong in line

        put_ttls="mail.smtp.strarttls.enable";

So I have change it to

 put_ttls="mail.smtp.starttls.enable";