package cn.primeledger.bank.service.core.mc.service; import cn.primeledger.bank.service.core.mc.exception.MailException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.List; import java.util.Properties; /** * Mail sending interface (the init function must be called before use) */ @Service public class MailSenderService { private Logger LOGGER = LoggerFactory.getLogger(MailSenderService.class); //mail server address @Value("${mail.smtp.username}") private String username; //mail server address @Value("${mail.smtp.password}") private String password; //mail server address @Value("${mail.smtp.host}") private String host; //Send mail port @Value("${mail.smtp.port}") private String port; //Mail Session private Session session; /** * Initialize the mailbox sender */ private void init() { Properties props = new Properties(); //initialize props props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.starttls.enable", "true"); //Create a session, like logging in as a mailbox session = Session.getDefaultInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } /** * send email * * @param accept recipient email address * @param subject email subject * @param content email content * @throws MessagingException */ public void send(String accept, String subject, String content) { LOGGER.info("start into mail send. accept=[{}]", accept); //Initialize the mail server this.init(); //Create mime type mail final MimeMessage msg = new MimeMessage(session); try { // set sender msg.setFrom(new InternetAddress(username)); //set recipient msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(accept)); //set the email header msg.setSubject(subject, "utf-8"); //Set the email content and set the UTF-8 encoding msg.setContent(content, "text/html;charset=utf-8"); //send email Transport.send(msg); } catch (MessagingException e) { throw new MailException("Send mail, message delivery exception", e); } finally { LOGGER.info("end mail send. accept=[{}]", accept); } } /** * group email * * @param accepts recipient's email address * @param subject email subject * @param content email content * @throws MessagingException */ public void send(List<String> accepts, String subject, String content) { LOGGER.info("start into mails send. accept=[{}]", accepts); //Initialize the mail server this.init(); //Create mime type mail final MimeMessage msg = new MimeMessage(session); try { // set sender msg.setFrom(new InternetAddress(username)); //Set recipients int num = accepts.size(); InternetAddress[] addresses = new InternetAddress[num]; for (int i = 0; i < num; i++) { addresses[i] = new InternetAddress(accepts.get(i)); } msg.setRecipients(MimeMessage.RecipientType.TO, addresses); //set the email header msg.setSubject(subject, "text/html;charset=utf-8"); //set the email content msg.setContent(content, "text/html;charset=utf-8"); Transport.send(msg); } catch (MessagingException e) { throw new MailException("mass mailing, message delivery exception", e); } finally { LOGGER.info("end mails send. accept=[{}]", accepts); } } }
@Service public class MailSenderService { private Logger LOGGER = LoggerFactory.getLogger(MailSenderService.class); //mail server account private static String USERNAME; //mail server password private static String PASSWORD; //mail server URL private static String HOST; //Send mail port private static String PORT; //spring boot cannot inject static properties, so you can do this @Value("${mail.smtp.username}") public void setUsername(String username) { USERNAME = username; } @Value("${mail.smtp.password}") public void setPassword(String password) { PASSWORD = password; } @Value("${mail.smtp.host}") public void setHost(String host) { HOST = host; } @Value("${mail.smtp.port}") public void setPort(String port) { PORT = port; } // mail sender @Value("${mail.smtp.from}") private String from; //mail sender name @Value("${mail.smtp.fromname}") private String fromname; //Mail Session private static Session session; /** * Initialize the mailbox sender */ private static void init() { // configure javamail Properties props = System.getProperties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.host", HOST); props.setProperty("mail.smtp.port", PORT); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.connectiontimeout", "180"); props.setProperty("mail.smtp.timeout", "600"); props.setProperty("mail.mime.encodefilename", "true"); session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(USERNAME, PASSWORD); } }); } /** * Set up mail * * @param message * @param subject * @param content * @throws UnsupportedEncodingException * @throws MessagingException */ private void setMessage(MimeMessage message, String subject, String content) throws UnsupportedEncodingException, MessagingException { // sender message.setFrom(new InternetAddress(from, fromname, "UTF-8")); // Email Subject message.setSubject(subject, "UTF-8"); // Mail type: plain text and hypertext coexist. Multipart multipart = new MimeMultipart("alternative"); // Add the email body in html form String html = "<html><head></head><body>" + content + "</body></html> "; BodyPart contentPart = new MimeBodyPart(); contentPart.setHeader("Content-Type", "text/html;charset=UTF-8"); contentPart.setHeader("Content-Transfer-Encoding", "base64"); contentPart.setContent(html, "text/html;charset=UTF-8"); multipart.addBodyPart(contentPart); message.setContent(multipart); } /** * send email * * @param accept recipient email address * @param subject email subject * @param content email content * @throws MessagingException */ public void send(String accept, String subject, String content) { LOGGER.info("start into mail send. accept=[{}]", accept); //Initialize the mail server this.init(); try { //Create mime type mail MimeMessage message = new MimeMessage(session); //set mail setMessage(message, subject, content); // receiver's address message.addRecipient(Message.RecipientType.TO, new InternetAddress(accept)); // Connect to the sendcloud server and send emails SMTPTransport transport = (SMTPTransport) session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getRecipients(MimeMessage.RecipientType.TO)); transport.close(); } catch (Exception e) { LOGGER.error("sender mail fail", e); MonitorLogUtils.logMonitorInfo(MonitorTarget.MAIL_SENDER_ERROR, TargetInfoType.INT, 1); throw new MailException("sender mail fail",e); } } /** * group email * * @param accepts recipient's email address * @param subject email subject * @param content email content * @throws MessagingException */ public void send(List<String> accepts, String subject, String content) { LOGGER.info("start into mails send. accept=[{}]", accepts); //Initialize the mail server this.init(); //Create mime type mail final MimeMessage message = new MimeMessage(session); try { //set mail setMessage(message, subject, content); //Set recipients int num = accepts.size(); InternetAddress[] addresses = new InternetAddress[num]; for (int i = 0; i < num; i++) { addresses[i] = new InternetAddress(accepts.get(i)); } message.setRecipients(MimeMessage.RecipientType.TO, addresses); // Connect to the sendcloud server and send emails SMTPTransport transport = (SMTPTransport) session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getRecipients(MimeMessage.RecipientType.TO)); transport.close(); } catch (Exception e) { LOGGER.error("sender mails fail", e); MonitorLogUtils.logMonitorInfo(MonitorTarget.MAIL_SENDER_ERROR, TargetInfoType.INT, 1); throw new MailException("sender mails fail", e); } finally { LOGGER.info("end mails send. accept=[{}]", accepts); } } }