Skip to content

Instantly share code, notes, and snippets.

@mox601
Last active October 2, 2015 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mox601/a1a09b17e30e71bca817 to your computer and use it in GitHub Desktop.
Save mox601/a1a09b17e30e71bca817 to your computer and use it in GitHub Desktop.
// 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