Last active
October 2, 2015 12:26
-
-
Save mox601/a1a09b17e30e71bca817 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// TODO make this call async, using another threadpool | |
public void sendEmail(final String sender, final String to, final String subject, | |
final String content, final String contentType) { | |
// null checks | |
connectToSmtpTransport(); | |
try { | |
//TODO from string to internet address | |
final InternetAddress senderAddress = emailContactToInternetAddress(sender); | |
//TODO from string to internet address | |
final InternetAddress toAddress = emailContactToInternetAddress(to); | |
//session is a field | |
final MimeMessage message = new MimeMessage(this.session); | |
message.setFrom(senderAddress); | |
final Address[] senders = new Address[] { senderAddress }; | |
message.setReplyTo(senders); | |
message.addRecipient(Message.RecipientType.TO, toAddress); | |
message.setSubject(subject); | |
message.setContent(content, contentType); | |
//smtpTransport is a field | |
this.smtpTransport.sendMessage(message, message.getAllRecipients()); | |
} catch (MessagingException mex) { | |
throw new RuntimeException(mex); | |
} catch (UnsupportedEncodingException e) { | |
throw new RuntimeException(e); | |
} finally { | |
closeQuietlySmtpTransport(); | |
} | |
LOGGER.info("message sent successfully to '" + to + "'"); | |
} | |
private void connectToSmtpTransport() { | |
try { | |
this.smtpTransport.connect(this.smtpHost, this.port, this.user, this.password); | |
} catch (NoSuchProviderException e) { | |
throw new RuntimeException(e); | |
} catch (MessagingException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
private void closeQuietlySmtpTransport() { | |
try { | |
this.smtpTransport.close(); | |
} catch (MessagingException e) { | |
LOGGER.warn("exception closing smtp transport: " + e.getMessage()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment