--- title: 'Spring Boot 寄信' disqus: hackmd --- ###### tags: `SpringBoot` Spring Boot 寄信 === [TOC] # 適用場景 分成兩種cases 1. 需要在信件中附上html content在裡面 2. 需要在信件中附上html content在裡面,且夾帶檔案 # 思考路徑 # 檔案結構目錄 # 程式碼部分 ## 寄信的主體 ```java= package com.allproducts.ai_center.business.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.map.HashedMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.allproducts.ai_center.email.service.MailHTMLContentBuilder; import com.allproducts.ai_center.exportdatabean.JoinAI_RatioBean; import Module.Email.Utility.EmailService.EmailService; @Service public class DemoThymeleafTable_SERVICE { private static Logger logger = LoggerFactory.getLogger(DemoThymeleafTable_SERVICE.class); @Autowired EmailService emailService; @Autowired MailHTMLContentBuilder mailHTMLContentBuilder; // help us use thylmeleaf public void sayHI() { logger.info("HI"); System.out.println("HI"); } public List <JoinAI_RatioBean> giveMeJoinAI_RatioBeanListData( ) { List <JoinAI_RatioBean> myList = new ArrayList<JoinAI_RatioBean>() ; JoinAI_RatioBean data1= new JoinAI_RatioBean("A","AP1583","mike",0,0, null ); JoinAI_RatioBean data2= new JoinAI_RatioBean("A","AP1582","sandy",85,90, null ); JoinAI_RatioBean data3= new JoinAI_RatioBean("B","AP1587","mike",52,25, null ); JoinAI_RatioBean data4= new JoinAI_RatioBean("B","AP1587","Robin",52,25, null ); JoinAI_RatioBean data5= new JoinAI_RatioBean("B","AP1587","ELmo",52,25, null ); myList.add(data1); myList.add(data2); myList.add(data3); myList.add(data4); myList.add(data5); return myList; } public void demoThymeleafTemplateWithTable() { String[] toPrimaryString =new String[] {"mike@tradeserv.com","robin@tradeserv.com"}; String[] toCcStrings =null; String subjectString ="Demo Sending HTML"; String templateFilePathString="DemoThymeleafTemplateWithTableControl.html"; //Data List <JoinAI_RatioBean> myDataList = giveMeJoinAI_RatioBeanListData( ); for (JoinAI_RatioBean each: myDataList) { logger.info(each.toString()); } // Thymeleaf model Map<String, Object> templateModelValueMap=new HashMap<>(); templateModelValueMap.put("title", "d"); templateModelValueMap.put("mydataList", myDataList); String mailHTMLBodyString=mailHTMLContentBuilder.generateMailContent(templateFilePathString, templateModelValueMap); emailService.sendHTMLMail(subjectString,mailHTMLBodyString,toPrimaryString); } public void demoThymeleafTemplateWithTable2() { String[] toPrimaryString =new String[] {"mike@tradeserv.com","robin@tradeserv.com"}; String[] toCcStrings =null; String subjectString ="Demo Sending HTML"; String templateFilePathString="DemoThymeleafTemplateWithTableControl.html"; //Data List <JoinAI_RatioBean> myDataList = giveMeJoinAI_RatioBeanListData( ); for (JoinAI_RatioBean each: myDataList) { logger.info(each.toString()); } // Thymeleaf model Map<String, Object> templateModelValueMap=new HashMap<>(); templateModelValueMap.put("title", "d"); templateModelValueMap.put("mydataList", myDataList); String mailHTMLBodyString=mailHTMLContentBuilder.generateMailContent(templateFilePathString, templateModelValueMap); emailService.sendHTMLMail(subjectString,mailHTMLBodyString,toPrimaryString); } } ``` ## MailHTMLContentBuilder ```java= package com.allproducts.ai_center.email.service; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; @Service public class MailHTMLContentBuilder { Logger LOG = LoggerFactory.getLogger(MailHTMLContentBuilder.class); private TemplateEngine templateEngine; @Autowired public MailHTMLContentBuilder(TemplateEngine templateEngine) { this.templateEngine = templateEngine; } public String generateMailContent(String templateFilePath, Map<String, Object> templateModelValueMap) { Context context = new Context(); context.setVariables(templateModelValueMap); return templateEngine.process(templateFilePath, context); } } ``` ## EmailService ```java= package Module.Email.Utility.EmailService; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.List; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; @Service public class EmailService { Logger logger = LoggerFactory.getLogger(EmailService.class); @Autowired private JavaMailSender javaMailSender; public void sendMail(String subject, String mailContent, String... toEmail) { try { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setTo(toEmail); mailMessage.setSubject(subject); mailMessage.setText(mailContent); mailMessage.setFrom("AllProduct-ENG@API-Team.com"); javaMailSender.send(mailMessage); } catch(Exception e) { logger.error("[EmailService]--sendMail() Exception happened..."); logger.error(e.toString()); } }//End function public void sendAttachmentsMail(String subject, String mailContent, List<EmailAttachFileBean> attachFilesBean, String... toEmail) { try { System.setProperty("mail.mime.splitlongparameters", "false"); MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,StandardCharsets.UTF_8.name()); helper.setTo(toEmail); helper.setSubject(subject); helper.setText(mailContent); helper.setFrom("AllProduct-ENG@API-Team.com"); for(EmailAttachFileBean eachAttachedFile : attachFilesBean) { FileSystemResource file = new FileSystemResource(new File(eachAttachedFile.getFileFullPath())); helper.addAttachment(MimeUtility.encodeWord(eachAttachedFile.getFileName(),"utf-8","B"), file); } javaMailSender.send(mimeMessage); } catch(Exception e) { logger.error("[EmailService]--sendAttachmentsMail() Exception happened..."); logger.error(e.toString()); } }//End function public void sendHTMLMail(String subject, String mailContent, String... toEmail) { try { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,StandardCharsets.UTF_8.name()); helper.setTo(toEmail); helper.setSubject(subject); helper.setText(mailContent,true); helper.setFrom("AllProduct-ENG@API-Team.com"); javaMailSender.send(mimeMessage); } catch(Exception e) { logger.error("[EmailService]--sendHTMLMail() Exception happened..."); logger.error(e.toString()); } }//End public void sendHTMLWithAttachmentsMail(String subject, String mailContent, List<EmailAttachFileBean> attachFilesBean, String... toEmail) { try { System.setProperty("mail.mime.splitlongparameters", "false"); MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,StandardCharsets.UTF_8.name()); helper.setTo(toEmail); helper.setSubject(subject); helper.setText(mailContent, true); helper.setFrom("AllProduct-ENG@API-Team.com"); for(EmailAttachFileBean eachAttachedFile : attachFilesBean) { FileSystemResource file = new FileSystemResource(new File(eachAttachedFile.getFileFullPath())); helper.addAttachment(MimeUtility.encodeWord(eachAttachedFile.getFileName(),"utf-8","B"), file); } javaMailSender.send(mimeMessage); } catch(Exception e) { logger.error("[EmailService]--sendHTMLWithAttachmentsMail() Exception happened..."); logger.error(e.toString()); } }//End function }//End class ``` ## EmailAttachFileBean ```java= package Module.Email.Utility.EmailService; public class EmailAttachFileBean { private String fileFullPath; private String fileName; private String fileTypeExtension; private String inlineContentId; public EmailAttachFileBean() { super(); // TODO Auto-generated constructor stub } public EmailAttachFileBean(String fileFullPath, String fileName, String fileTypeExtension, String inlineContentId) { super(); this.fileFullPath = fileFullPath; this.fileName = fileName; this.fileTypeExtension = fileTypeExtension; this.inlineContentId = inlineContentId; } public String getFileFullPath() { return fileFullPath; } public void setFileFullPath(String fileFullPath) { this.fileFullPath = fileFullPath; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileTypeExtension() { return fileTypeExtension; } public void setFileTypeExtension(String fileTypeExtension) { this.fileTypeExtension = fileTypeExtension; } public String getInlineContentId() { return inlineContentId; } public void setInlineContentId(String inlineContentId) { this.inlineContentId = inlineContentId; } }// End class ``` # 參考連結