Skip to content

Instantly share code, notes, and snippets.

@paulbrodner
Created October 17, 2019 10:13
Show Gist options
  • Select an option

  • Save paulbrodner/be07f1e87e5fcafea4b7c6bb4a530e32 to your computer and use it in GitHub Desktop.

Select an option

Save paulbrodner/be07f1e87e5fcafea4b7c6bb4a530e32 to your computer and use it in GitHub Desktop.
package com.paulbrodner.buddy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
@Configuration
@ConfigurationProperties("mail")
public class MailNotifier {
Logger logger = LoggerFactory.getLogger(MailNotifier.class);
private Session session;
private String username;
private String password;
private String to;
@PostConstruct
private void defineSession() {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(getUsername(), getPassword());
}
});
}
public void sendNotification(String subject, String body) {
logger.info("Sending email notification TO: {}, with Subject: {}", getTo(), subject);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(getUsername()));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo()));
message.setSubject(subject);
message.setContent(body, "text/html; charset=utf-8");
Transport.send(message);
logger.info("Notification Sent!");
} catch (MessagingException e) {
logger.error("Cannot sent Mail notification: {}", e.getMessage());
}
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
}
/*
<!-- notification -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment