dnet-applications/libs/dnet-is-services/src/main/java/eu/dnetlib/notifications/mail/EmailDispatcher.java

148 lines
4.5 KiB
Java

package eu.dnetlib.notifications.mail;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import javax.annotation.PostConstruct;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.google.common.base.Splitter;
import eu.dnetlib.manager.wf.repository.EmailTemplateRepository;
@Service
public class EmailDispatcher {
private static final Log log = LogFactory.getLog(EmailDispatcher.class);
private final BlockingQueue<Message> queue = new LinkedBlockingQueue<>();
@Value("${'dnet.configuration.mail.sender.email'}")
private String from;
@Value("${'dnet.configuration.mail.sender.name'}")
private String fromName;
@Value("${'dnet.configuration.mail.cc'}")
private String cc;
@Value("${'dnet.configuration.mail.smtp.host'}")
private String smtpHost;
@Value("${'dnet.configuration.mail.smtp.port'}")
private final int smtpPort = 587;
@Value("${'dnet.configuration.mail.smtp.user'}")
private String smtpUser;
@Value("${'dnet.configuration.mail.smtp.password'}")
private String smtpPassword;
@Value("${'dnet.configuration.baseUrl'}")
private String baseUrl;
@Value("${'dnet.configuration.infrastructure'}")
private String infrastructure;
@Autowired
private EmailTemplateRepository emailTemplateRepository;
@PostConstruct
private void init() {
new Thread(() -> {
while (true) {
try {
final Message message = this.queue.take();
if (message != null) {
try {
log.info("Sending mail...");
Transport.send(message);
log.info("...sent");
} catch (final MessagingException e) {
log.error("Error sending email", e);
this.queue.add(message);
}
}
} catch (final InterruptedException e1) {
throw new RuntimeException(e1);
}
}
}).run();
}
public void sendMail(final String to, final String subject, final String message) {
try {
final Session session = Session.getInstance(obtainProperties(), obtainAuthenticator());
final MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(this.from, this.fromName));
mimeMessage.setSubject(subject);
mimeMessage.setContent(message, "text/html; charset=utf-8");
mimeMessage.setSentDate(new Date());
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
if (this.cc != null && !this.cc.isEmpty()) {
for (final String aCC : Splitter.on(",").omitEmptyStrings().trimResults().split(cc)) {
mimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(aCC));
}
}
this.queue.add(mimeMessage);
log.info("Mail to " + to + " in queue");
} catch (final Exception e) {
log.error("Error sending mail", e);
}
}
public void sendStoredMail(final String to, final String emailId, final Map<String, Object> params) {
// TODO use a real template library
emailTemplateRepository.findById(emailId).ifPresent(tmpl -> {
String msg = tmpl.getMessage();
String subject = tmpl.getSubject();
for (final Entry<String, Object> e : params.entrySet()) {
msg = msg.replaceAll("{" + e.getKey() + "}", e.getValue().toString());
subject = subject.replaceAll("{" + e.getKey() + "}", e.getValue().toString());
}
sendMail(to, subject, msg);
});
}
private Properties obtainProperties() {
final Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", this.smtpHost);
props.put("mail.smtp.port", this.smtpPort);
props.put("mail.smtp.auth", Boolean.toString(this.smtpUser != null && !this.smtpUser.isEmpty()));
return props;
}
private Authenticator obtainAuthenticator() {
if (this.smtpUser == null || this.smtpUser.isEmpty()) { return null; }
return new Authenticator() {
private final PasswordAuthentication authentication = new PasswordAuthentication(EmailDispatcher.this.smtpUser, EmailDispatcher.this.smtpPassword);
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return this.authentication;
}
};
}
}