История изменений
Исправление Nagwal, (текущая версия) :
Да, возможно, гуглить по слову javax.mail
Вот пример, правда не standalone а сконфигуренный спрингом бин, да еще и freemarker использующий для шаблонизации, но думаю разберешся
package ru.visang.services;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import ru.visang.commons.exceptions.ExpectedException;
import ru.visang.commons.utils.LambdaUtils;
import javax.annotation.PostConstruct;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import static java.util.stream.Collectors.joining;
import static ru.visang.commons.utils.LambdaUtils.doUnsafe;
/**
* Email sending service.
*
*
* Created by Antony on 12.11.2014.
*/
@Service
public class NotificationService {
@Value("${email.smtp.hostname}")
private String hostname;
@Value("${email.smtp.port}")
private Integer port;
@Value("${email.smtp.login}")
private String login;
@Value("${email.smtp.password}")
private String password;
@Value("${email.smtp.use_tls}")
private Boolean usetls;
@Value("${email.smtp.use_auth}")
private Boolean auth;
@Value("${email.mail.from}")
private String mailFrom;
@Value("${email.enabled}")
private boolean enabled;
@Value("${email.template.path}")
private String templateDir;
private Session session;
private Configuration fmConfig;
private Logger log = LoggerFactory.getLogger(getClass());
@PostConstruct
protected void init() {
if (enabled) {
log.info("=====> Initializing Email notification service.");
fmConfig = new Configuration();
fmConfig.setDefaultEncoding("UTF-8");
try {
fmConfig.setDirectoryForTemplateLoading(new File(templateDir));
} catch (IOException e) {
log.error("======> Cannot set base directory for email notifications templates lookup.", e);
throw new ExceptionInInitializerError();
}
Properties props = new Properties();
props.put("mail.smtp.auth", auth.toString());
props.put("mail.smtp.starttls.enable", usetls.toString());
props.put("mail.smtp.host", hostname);
props.put("mail.smtp.port", port.toString());
if (auth) {
session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(login, password);
}
});
} else {
session = Session.getInstance(props);
}
} else {
log.warn("=====> Email notifications are disabled.");
}
}
/**
* Enumeration of available notification types.
*/
public static enum Type {
FMS_SENT("fms_sent.ftl"), FMS_ACCEPTED("fms_accepted.ftl"), FMS_REJECTED("fms_rejected.ftl");
private String template;
Type(String template) {
this.template = template;
}
public String template() {
return template;
}
}
/**
* Send notifications to all acceptors
*
* @param type Type of notification
* @param acceptors List of acceptors
* @param properties Properties that should be substituted in template for this notification type
*/
public void sendNotifications(Type type, List<String> acceptors, Map<String, Object> properties) {
if (!enabled) return;
Objects.requireNonNull(acceptors, "Acceptors list cannot be null.");
Objects.requireNonNull(properties, "Properties cannot be null.");
try {
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(mailFrom));
// Set To: header field of the header.
acceptors.forEach(a -> doUnsafe(() -> message.addRecipient(Message.RecipientType.TO, new InternetAddress(a))));
// Set Subject: header field
message.setSubject("Visareg.ru notification!");
Template template = fmConfig.getTemplate(type.template());
StringWriter stringWriter = new StringWriter();
template.process(properties, stringWriter);
// Send the actual HTML message, as big as you like
message.setContent(stringWriter.toString(), "text/html");
// Send message
Transport.send(message);
} catch (MessagingException | IOException e) {
log.error("=====> Error sending notification {} to users: {}. Error: {}", type.name(), acceptors.stream().collect(joining(", ")), e.getMessage());
} catch (TemplateException e) {
log.error("=====> Error sending notification {} to users: {}", type.name(), acceptors.stream().collect(joining(", ")), e);
throw new ExpectedException("Template processing error.", e); //Let us fail if we have an error in template.
}
}
}
Исходная версия Nagwal, :
Да, возможно, гуглить по слову javax.mail
Вот пример, правда не standalone а сконфигуренный спрингом бин, да еще и freemarker использующий для шаблонизации, но думаю разберешся
package ru.visang.services;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import ru.visang.commons.exceptions.ExpectedException;
import ru.visang.commons.utils.LambdaUtils;
import javax.annotation.PostConstruct;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import static java.util.stream.Collectors.joining;
import static ru.visang.commons.utils.LambdaUtils.doUnsafe;
/**
* Email sending service.
*
* This service can be used only form Controllers, not root Services because of dependency on FreemarkerViewResolver,
* that needs to be initialized in WebContext to let it search for templates in a web folder and not only in classpath.
*
* Created by Antony on 12.11.2014.
*/
@Service
public class NotificationService {
@Value("${email.smtp.hostname}")
private String hostname;
@Value("${email.smtp.port}")
private Integer port;
@Value("${email.smtp.login}")
private String login;
@Value("${email.smtp.password}")
private String password;
@Value("${email.smtp.use_tls}")
private Boolean usetls;
@Value("${email.smtp.use_auth}")
private Boolean auth;
@Value("${email.mail.from}")
private String mailFrom;
@Value("${email.enabled}")
private boolean enabled;
@Value("${email.template.path}")
private String templateDir;
private Session session;
private Configuration fmConfig;
private Logger log = LoggerFactory.getLogger(getClass());
@PostConstruct
protected void init() {
if (enabled) {
log.info("=====> Initializing Email notification service.");
fmConfig = new Configuration();
fmConfig.setDefaultEncoding("UTF-8");
try {
fmConfig.setDirectoryForTemplateLoading(new File(templateDir));
} catch (IOException e) {
log.error("======> Cannot set base directory for email notifications templates lookup.", e);
throw new ExceptionInInitializerError();
}
Properties props = new Properties();
props.put("mail.smtp.auth", auth.toString());
props.put("mail.smtp.starttls.enable", usetls.toString());
props.put("mail.smtp.host", hostname);
props.put("mail.smtp.port", port.toString());
if (auth) {
session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(login, password);
}
});
} else {
session = Session.getInstance(props);
}
} else {
log.warn("=====> Email notifications are disabled.");
}
}
/**
* Enumeration of available notification types.
*/
public static enum Type {
FMS_SENT("fms_sent.ftl"), FMS_ACCEPTED("fms_accepted.ftl"), FMS_REJECTED("fms_rejected.ftl");
private String template;
Type(String template) {
this.template = template;
}
public String template() {
return template;
}
}
/**
* Send notifications to all acceptors
*
* @param type Type of notification
* @param acceptors List of acceptors
* @param properties Properties that should be substituted in template for this notification type
*/
public void sendNotifications(Type type, List<String> acceptors, Map<String, Object> properties) {
if (!enabled) return;
Objects.requireNonNull(acceptors, "Acceptors list cannot be null.");
Objects.requireNonNull(properties, "Properties cannot be null.");
try {
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(mailFrom));
// Set To: header field of the header.
acceptors.forEach(a -> doUnsafe(() -> message.addRecipient(Message.RecipientType.TO, new InternetAddress(a))));
// Set Subject: header field
message.setSubject("Visareg.ru notification!");
Template template = fmConfig.getTemplate(type.template());
StringWriter stringWriter = new StringWriter();
template.process(properties, stringWriter);
// Send the actual HTML message, as big as you like
message.setContent(stringWriter.toString(), "text/html");
// Send message
Transport.send(message);
} catch (MessagingException | IOException e) {
log.error("=====> Error sending notification {} to users: {}. Error: {}", type.name(), acceptors.stream().collect(joining(", ")), e.getMessage());
} catch (TemplateException e) {
log.error("=====> Error sending notification {} to users: {}", type.name(), acceptors.stream().collect(joining(", ")), e);
throw new ExpectedException("Template processing error.", e); //Let us fail if we have an error in template.
}
}
}