天天看點

springboot項目實作郵件發送功能

1.yml檔案配置

springboot項目實作郵件發送功能

2.pom檔案導入jar包

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
           

3.郵件結構實體類

@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel("郵件消息結構")
public class EmailInfo {
    @ApiModelProperty(value = "郵件主題")
    private String subject;

    @ApiModelProperty(value = "郵件正文")
    private String contentHtmlString;

    @ApiModelProperty(value = "主送人")
    private String to;

    @ApiModelProperty(value = "抄送人")
    private String cc;

    @ApiModelProperty(value = "密送人")
    private String bcc;

    @ApiModelProperty(value = "附件")
    private String[] files;

    @ApiModelProperty(value = "預定資訊")
    private Map<String,Object> dateMap;
    }
           

4.service層代碼,controller層省略

public ISceneResponse sendEmail(EmailInfo emailInfo) {
		return sendEmail(emailInfo.getSubject(), emailInfo.getContentHtmlString(), emailInfo.getTo(), emailInfo.getCc(),
				emailInfo.getBcc(), emailInfo.getFiles());
	}
           
@Override
public ISceneResponse sendEmail(String subject, String contentHtmlString, String to, String cc, String bcc,
		String[] files) {
	try {
		if (to.isEmpty()) {
			return ISceneResponse.fail("郵件發送人不能為空");
		}
		MimeMessage mimeMessage = javaMailSender.createMimeMessage();
		MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
		mimeMessageHelper.setFrom(username);
		String[] tos = getStringSplite(to);
		String[] ccs = getStringSplite(cc);
		String[] bccs = getStringSplite(bcc);
		if (tos == null) {
			return ISceneResponse.fail("郵件發送人格式錯誤");
		}
		mimeMessageHelper.setTo(tos);
		if (ccs != null) {
			mimeMessageHelper.setCc(ccs);
		}
		if (bccs != null) {
			mimeMessageHelper.setBcc(bccs);
		}
		mimeMessageHelper.setSubject(subject);
		contentHtmlString = Optional.ofNullable(contentHtmlString).orElse("");
		mimeMessageHelper.setText(contentHtmlString, true);

		if (files != null && files.length != 0) {
			for (String filePath : files) {
				FileSystemResource file = new FileSystemResource(filePath);
				mimeMessageHelper.addAttachment(file.getFilename(), file);
			}
		}
		javaMailSender.send(mimeMessage);
	} catch (Exception e) {
		logger.info("[EmailService.sendEmail] error", e);
		return ISceneResponse.error(e);
	}

	return ISceneResponse.success();
}

// 将發送人序列字元串按逗号分解
private String[] getStringSplite(String to) {
	if (StringUtils.isEmpty(to)) {
		return null;
	}
	return to.split(",");
}
           

代碼中"userName"是yml檔案中配的,通過以下代碼擷取。

@Value("${spring.mail.username}")
	private String username;
           

5.利用FreeMarker發送郵件

上述代碼可以實作簡單的郵件通知,但是内容比較單一,若郵件需要圖表等複雜的表現形式,則需要通過模闆去實作,下面的代碼是利用FreeMarker模闆引擎來豐富郵件内容。

public ISceneResponse sendFreeMarkerEmail(EmailInfo emailInfo) {
		String htmlText = "";
		Map<String,Object> dateMap = emailInfo.getDateMap();
		try {
			Configuration configuration = new Configuration(Configuration.VERSION_2_3_27);
			configuration.setClassForTemplateLoading(this.getClass(), "/templates");
			htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("orderHtml.ftl"), dateMap);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		return sendEmail(emailInfo.getSubject(), htmlText, emailInfo.getTo(), emailInfo.getCc(),
				emailInfo.getBcc(), emailInfo.getFiles());
	}
           

因為項目是前後端分離,郵件模闆ftl檔案直接放在了後端resource目錄下。

springboot項目實作郵件發送功能

service層導包:

import freemarker.template.Configuration;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
           

6.解決群發郵件一個郵箱位址錯誤,其他人接收不到郵件問題

解決思路:通過擷取異常資訊中的錯誤郵箱,将其踢出收件人(抄送人)組,再次調用發送接口。

try{
	//發送郵件代碼
}catch (MailSendException e) {
      logger.error("發送MimeMessge時發生異常!", e);
      Set tmpInvalidMails = getInvalidAddress(e);
      // 非無效收件人導緻的異常,暫不處理
      if (tmpInvalidMails.isEmpty()){
          logger.error(e.getMessage());
          msg = e.getMessage();
      }else {
          logger.info(setToStr(tmpInvalidMails)+"郵箱位址錯誤!");
          String tos = removeAll(emailInfo.getTo(),tmpInvalidMails);
          String ccs = removeAll(emailInfo.getCc(),tmpInvalidMails);
          if(tos != null){
              emailInfo.setCc(ccs);
              emailInfo.setTo(tos);
              sendMimeMessge(emailInfo);
          }
      }
  } catch (MessagingException e) {
      e.printStackTrace();
  }
 
 //移除錯誤的郵箱位址
 private String removeAll(String to, Set tmpInvalidMails) {
        String result = null;
        String[] toArr = getStringSplite(to);
        List<String> list = Arrays.asList(toArr);
        List newLsit = new ArrayList(list);
        newLsit.removeAll(tmpInvalidMails);
        result = listToStr(newLsit);
        return result;
 }
 
//List轉String
public static String listToStr(List<String> mList) {
    String result= null;
    if (null != mList && mList.size() > 0) {
        String[] mListArray = mList.toArray(new String[mList.size()]);
        for (int i = 0; i < mListArray.length; i++) {
	        if (i < mListArray.length - 1) {
	            result+= mListArray[i] + ",";
	        } else {
	            result+= mListArray[i];
	        }
        }
     }
     return result;
}
           

繼續閱讀