I am trying to send a mail when the user clicks a button. But when I click the same once again, an exception occurs like
Mail Exception :Could not connect to SMTP host: smtp.gmail.com, port: 587
Properties code:
props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");
Message Code:
session =
Session.getDefaultInstance(
props,
new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(
MailIntegrationFromAddress.getText().trim(),
MailIntegrationFromAddressPassword.getText().trim()); // change accordingly
}});
try {
message.setFrom( new InternetAddress( MailIntegrationFromAddress.getText()));
message.addRecipient( Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Subject type");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Message Body");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String filename = FileLocation.getText();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
message.saveChanges();
setCursor(new Cursor(Cursor.WAIT_CURSOR));
Transport.send(message);
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
JOptionPane.showMessageDialog(null, "Mail sent Successfully... :-)");
The mail function works fine for the first time but it fails while calling in the second time.
TLS provides authentication over an encrypted channel instead of a less-secure clear channel
Replace
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
with
props.put("mail.smtp.starttls.enable", "true");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.