天天看点

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;
}
           

继续阅读