原创

Spring Boot(十二)集成spring-boot-starter-mail发送邮件


项目GitHub地址 :

https://github.com/FrameReserve/TrainingBoot


Spring Boot(十二)集成spring-boot-starter-mail发送邮件,标记地址:

https://github.com/FrameReserve/TrainingBoot/releases/tag/0.0.12



pom.xml

增加:

spring-boot-starter-mail

spring-boot-starter-velocity -- 模板

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

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


Spring Boot配置文件:

QQ邮箱权限需要在QQ邮箱里设置,163则不用,问题比较少。

src/main/resources/application.yml

    mail:
        host: smtp.163.com
        username: 286352250@163.com
        password: 用户密码
        properties:
            mail: 
                smtp:
                    auth: true
                    timeout: 25000



Email配置类:

后期经常使用发件人邮箱,在这统一定义。

 src/main/java/com/training/core/email/EmailConfig.java

package com.training.core.email;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Component
public class EmailConfig {

	/**
	 * 发件邮箱
	 */
	@Value("${spring.mail.username}")
	private String emailFrom;

	public String getEmailFrom() {
		return emailFrom;
	}

	public void setEmailFrom(String emailFrom) {
		this.emailFrom = emailFrom;
	}
	
}



定义Email Service,三种邮件风格:

1. 发送简单邮件。

2. 发送带附件简单邮件

3. 发送模板邮件。

src/main/java/com/training/core/email/EmailService.java

package com.training.core.email;

import java.io.File;
import java.util.List;
import java.util.Map;

import com.training.core.dto.Pair;

public interface EmailService {

	/**
	 * 发送简单邮件
	 * @param sendTo 收件人地址
	 * @param titel  邮件标题
	 * @param content 邮件内容
	 */
	public void sendSimpleMail(String sendTo, String titel, String content);
	
	/**
	 * 发送简单邮件
	 * @param sendTo 收件人地址
	 * @param titel  邮件标题
	 * @param content 邮件内容
	 * @param attachments<文件名,附件> 附件列表
	 */
	public void sendAttachmentsMail(String sendTo, String titel, String content, List<Pair<String, File>> attachments);
	
	/**
	 * 发送模板邮件
	 * @param sendTo 收件人地址
	 * @param titel  邮件标题
	 * @param content<key, 内容> 邮件内容
	 * @param attachments<文件名,附件> 附件列表
	 */
	public void sendTemplateMail(String sendTo, String titel, Map<String, Object> content, List<Pair<String, File>> attachments);
	
}


Email Service实现类:

src/main/java/com/training/core/email/EmailServiceImpl.java

package com.training.core.email;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.commons.collections.map.HashedMap;
import org.apache.velocity.app.VelocityEngine;
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.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.training.core.dto.Pair;
import com.training.core.exception.RuntimeServiceException;

@Service
public class EmailServiceImpl implements EmailService {

	@Autowired
	private EmailConfig emailConfig;
	@Autowired
	private JavaMailSender mailSender;
	@Autowired
	private VelocityEngine velocityEngine;
	
	public void sendSimpleMail(String sendTo, String titel, String content) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(emailConfig.getEmailFrom());
		message.setTo(sendTo);
		message.setSubject(titel);
		message.setText(content);
		mailSender.send(message);
	}

	public void sendAttachmentsMail(String sendTo, String titel, String content, List<Pair<String, File>> attachments) {

		MimeMessage mimeMessage = mailSender.createMimeMessage();

		try {
			MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
			helper.setFrom(emailConfig.getEmailFrom());
			helper.setTo(sendTo);
			helper.setSubject(titel);
			helper.setText(content);

			for (Pair<String, File> pair : attachments) {
				helper.addAttachment(pair.getLeft(), new FileSystemResource(pair.getRight()));
			}
		} catch (Exception e) {
			throw new RuntimeServiceException(e);
		}

		mailSender.send(mimeMessage);
	}

	public void sendInlineMail() {

		MimeMessage mimeMessage = mailSender.createMimeMessage();

		try {
			MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
			helper.setFrom(emailConfig.getEmailFrom());
			helper.setTo("286352250@163.com");
			helper.setSubject("主题:嵌入静态资源");
			helper.setText("<html><body><img src=/"cid:weixin/" ></body></html>", true);

			FileSystemResource file = new FileSystemResource(new File("weixin.jpg"));
			helper.addInline("weixin", file);
		} catch (Exception e) {
			throw new RuntimeServiceException(e);
		}

		mailSender.send(mimeMessage);
	}

	public void sendTemplateMail(String sendTo, String titel, Map<String, Object> content, List<Pair<String, File>> attachments) {

		MimeMessage mimeMessage = mailSender.createMimeMessage();

		try {
			MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
			helper.setFrom(emailConfig.getEmailFrom());
			helper.setTo(sendTo);
			helper.setSubject(titel);

			String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "template.vm", "UTF-8", content);
			helper.setText(text, true);
			
			for (Pair<String, File> pair : attachments) {
				helper.addAttachment(pair.getLeft(), new FileSystemResource(pair.getRight()));
			}
		} catch (Exception e) {
			throw new RuntimeServiceException(e);
		}

		mailSender.send(mimeMessage);
	}
}



测试邮件发送:

src/main/java/com/training/email/controller/DemoEmailController.java

package com.training.email.controller;

import io.swagger.annotations.ApiOperation;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.training.core.controller.BaseController;
import com.training.core.dto.ResultDataDto;
import com.training.core.email.EmailService;

@RestController
@RequestMapping(value="/email") 
public class DemoEmailController extends BaseController {

	@Resource
	private EmailService emailService;
	
	/**
	 * 测试邮件发送
	 */
	@ApiOperation(value="测试邮件发送", notes="getEntityById")
    @RequestMapping(value = "/getTestDemoEmail", method = RequestMethod.GET)
	public @ResponseBody ResultDataDto getEntityById() throws Exception {
		String sendTo = "1265400024@qq.com";
		String titel = "测试邮件标题";
		String content = "测试邮件内容";
		emailService.sendSimpleMail(sendTo, titel, content);
		return ResultDataDto.addSuccess();
	}
}















正文到此结束
Loading...