From bd2238dbb855bb3815af240ab2ee1ba6ff917579 Mon Sep 17 00:00:00 2001 From: Stian Thorgersen Date: Tue, 12 Apr 2016 07:06:50 +0200 Subject: [PATCH] KEYCLOAK-2770 Close mail transport after sending message --- .../keycloak/email/DefaultEmailSenderProvider.java | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/services/src/main/java/org/keycloak/email/DefaultEmailSenderProvider.java b/services/src/main/java/org/keycloak/email/DefaultEmailSenderProvider.java index dc35f392e1..a2469ec279 100644 --- a/services/src/main/java/org/keycloak/email/DefaultEmailSenderProvider.java +++ b/services/src/main/java/org/keycloak/email/DefaultEmailSenderProvider.java @@ -25,6 +25,7 @@ import org.keycloak.models.UserModel; import org.keycloak.services.ServicesLogger; import javax.mail.Message; +import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; @@ -54,6 +55,7 @@ public class DefaultEmailSenderProvider implements EmailSenderProvider { @Override public void send(RealmModel realm, UserModel user, String subject, String textBody, String htmlBody) throws EmailException { + Transport transport = null; try { String address = user.getEmail(); Map config = realm.getSmtpConfig(); @@ -114,7 +116,7 @@ public class DefaultEmailSenderProvider implements EmailSenderProvider { msg.saveChanges(); msg.setSentDate(new Date()); - Transport transport = session.getTransport("smtp"); + transport = session.getTransport("smtp"); if (auth) { transport.connect(config.get("user"), config.get("password")); } else { @@ -124,6 +126,14 @@ public class DefaultEmailSenderProvider implements EmailSenderProvider { } catch (Exception e) { logger.failedToSendEmail(e); throw new EmailException(e); + } finally { + if (transport != null) { + try { + transport.close(); + } catch (MessagingException e) { + logger.warn("Failed to close transport", e); + } + } } }