设置邮箱参数
private JavaMailSenderImpl getMailSender(String configPrefix) {
if (StringUtils.isEmpty(configPrefix))
configPrefix = "mail.";
else if (configPrefix.charAt(configPrefix.length() - 1) != '.')
configPrefix += '.';
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
Map<String, String> config;
if ("mail.".equals(configPrefix)) {
config = this.paramConfig.getConfigValueWithPrefix(configPrefix);
} else {
config = this.paramConfig.getConfigValueWithPrefix(configPrefix, true);
}
if (CollectionUtils.isEmpty(config)) {
return null;
}
prepareConfig(config);
mailSender.setDefaultEncoding("utf-8");
mailSender.setPassword(config.remove(EmailConstant.KEY_PASSWORD));
mailSender.setUsername(config.remove(EmailConstant.KEY_USER_NAME));
mailSender.setHost(config.remove(EmailConstant.KEY_MAIL_HOST));
mailSender.setPort(BeanUtils.convert(config.remove(EmailConstant.KEY_MAIL_HOST_PORT), -1, Integer.class));
mailSender.setJavaMailProperties(MapUtils.toProperties(config));
return mailSender;
}
public Boolean sendMail(EmailSenderEntity entity, String configPrefix) {
Assert.notNull(entity, "entity is required");
JavaMailSenderImpl sender = this.getMailSender(configPrefix);
if (sender == null) {
log.warn("No email send configurated.");
return false;
}
if (entity.getFrom() == null) {
Properties prop = sender.getJavaMailProperties();
String nick = prop.getProperty(EmailConstant.KEY_NICK);
String address = prop.getProperty(EmailConstant.KEY_MAIL_FROM);
entity.setFrom(EmailUtils.formatUserNameAddress(nick, address));
}
MimeMessage mimeMessage = sender.createMimeMessage();
try {
EmailUtils.prepareEmailMessage(mimeMessage, entity);
sender.send(mimeMessage);
} catch (Exception ex) {
log.error("EmailSenderService->sendMail:", ex);
return false;
}
return true;
}
public static void prepareEmailMessage(MimeMessage mimeMessage, EmailSenderEntity entity) throws Exception {
List<MultipartFile> files = entity.getFiles();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, !CollectionUtils.isEmpty(files));
if (entity.getFrom() != null) {
helper.setFrom(entity.getFrom());
}
if (!CollectionUtils.isEmpty(entity.getTo())) {
helper.setTo(entity.getTo().toArray(new String[0]));
}
if (!CollectionUtils.isEmpty(entity.getCc())) {
List<String> ccList = new ArrayList<>();
for (String cc : entity.getCc()) {
if (!StringUtils.isEmpty(cc)) {
ccList.add(cc);
}
}
if (!ccList.isEmpty())
helper.setCc(ccList.toArray(new String[0]));
}
helper.setSubject(BeanUtils.ifnull(entity.getSubject(), "无主题"));
if (entity.getBody() != null) {
helper.setText(entity.getBody(), entity.getBody().indexOf("<body>") > -1);
}
// 附件操作
if (files != null) {
for (MultipartFile file : files) {
MultipartFile mpf = (MultipartFile) file;
if (mpf.getSize() == 0) {
continue;
}
BytesDataSource ds = new BytesDataSource(mpf.getOriginalFilename(), mpf.getBytes());
ds.setContentType(mpf.getContentType());
helper.addAttachment(ds.getName(), ds);
}
}
}