Java tutorial
/* * Copyright 2015 dactiv * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.dactiv.fear.service.service.message; import com.github.dactiv.fear.commons.entity.Mail; import com.github.dactiv.fear.commons.exception.ServiceException; import org.apache.commons.collections.MapUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import java.io.File; import java.io.UnsupportedEncodingException; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; /** * ?? * * @author maurice */ @Service @Transactional public class MessageService implements InitializingBean { private final static Logger LOGGER = LoggerFactory.getLogger(MessageService.class); private final static String DEFAULT_MAIL_ENCODING = "UTF-8"; // ? runnable ?? @Autowired(required = false) private Executor executor; // ???? @Value("${mail.sender.name}") private String mailSenderName; // ?? @Value("${mail.account.path}") private Resource[] resources; // java mail ??? private List<JavaMailSender> javaMailSenders = new ArrayList<>(); // ?? private AtomicInteger sendMailIndex = new AtomicInteger(0); /** * ?? * * @param mail */ public void sendMail(final Mail mail) { if (executor != null) { executor.execute(new Runnable() { @Override public void run() { doSendMail(mailSenderName, mail); } }); } else { doSendMail(mailSenderName, mail); } } /** * ?? * * @param nickname ?? null * @param mail */ private void doSendMail(String nickname, Mail mail) { try { JavaMailSender mailSender = getJavaMailSender(); if (mailSender == null) { throw new ServiceException("???"); } MimeMessage msg = mailSender.createMimeMessage(); MimeMessageHelper helper; if (mailSender instanceof JavaMailSenderImpl) { JavaMailSenderImpl jmsi = (JavaMailSenderImpl) mailSender; helper = new MimeMessageHelper(msg, true, jmsi.getDefaultEncoding()); } else { helper = new MimeMessageHelper(msg, true); } helper.setTo(mail.getTo()); helper.setFrom(getSendForm(nickname, mailSender)); helper.setSubject(mail.getTitle()); helper.setText(mail.getContent(), mail.getHtml()); if (!MapUtils.isEmpty(mail.getAttachment())) { for (Map.Entry<String, File> entry : mail.getAttachment().entrySet()) { helper.addAttachment(entry.getKey(), entry.getValue()); } } mailSender.send(msg); LOGGER.info("???"); } catch (Exception e) { LOGGER.error("??", e); } } /** * ??? * * @param nickname * @param javaMailSender ?? * * @return ?? */ private String getSendForm(String nickname, JavaMailSender javaMailSender) { JavaMailSenderImpl impl = null; if (javaMailSender instanceof JavaMailSenderImpl) { impl = (JavaMailSenderImpl) javaMailSender; } if (impl == null) { throw new ServiceException( JavaMailSenderImpl.class + " ?? " + javaMailSender.getClass() + ""); } String address; String propertiesNickname = impl.getJavaMailProperties().getProperty("mail.nickname", nickname); try { if (StringUtils.isEmpty(propertiesNickname)) { address = impl.getUsername(); } else { address = MimeUtility.encodeText(propertiesNickname) + " <" + impl.getUsername() + ">"; } } catch (UnsupportedEncodingException e) { LOGGER.warn("?[" + nickname + "],?" + impl.getUsername() + "", e); address = impl.getUsername(); } return address; } /** * ??? * * @return ?? */ private JavaMailSender getJavaMailSender() { int index = sendMailIndex.get(); if (index + 1 > javaMailSenders.size()) { sendMailIndex.compareAndSet(index, 0); } return javaMailSenders.get(sendMailIndex.getAndIncrement()); } /** * spring ??????. * @throws Exception */ @Override public void afterPropertiesSet() throws Exception { for (Resource r : resources) { JavaMailSenderImpl jms = new JavaMailSenderImpl(); Properties properties = new Properties(); properties.load(r.getInputStream()); jms.setUsername(properties.getProperty("mail.username")); jms.setPassword(properties.getProperty("mail.password")); jms.setHost(properties.getProperty("mail.host")); jms.setDefaultEncoding(properties.getProperty("mail.default.encoding", DEFAULT_MAIL_ENCODING)); jms.setJavaMailProperties(properties); javaMailSenders.add(jms); } } }