spring boot 整合邮箱

Maven包依赖

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

配置application.yml

spring:
    #邮箱
  mail:
    host: smtp.qq.com
    username: 2269472297@qq.com
    #QQ邮箱的授权码
    password: yztfquoomtrvebgd
    default-encoding: UTF-8
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true

接着写一个工具类

@Component
public class MailConfig
{

	@Autowired
	private JavaMailSenderImpl mailSender;

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

	/**
	 * 发送纯文本形式的email
	 * 
	 * @param toEmail
	 *            收件人邮箱
	 * @param title
	 *            邮件标题
	 * @param content
	 *            邮件内容
	 */
	public void sendTextMail(String toEmail, String title, String content)
	{
		SimpleMailMessage msg = new SimpleMailMessage();
		msg.setFrom(username);
		msg.setTo(toEmail);
		msg.setSubject(title);
		msg.setText(content);
		mailSender.send(msg);
	}

	/**
	 * 发送带有html的内容
	 * 
	 * @param userId
	 * @throws MessagingException
	 */
	public void sendHtmlMail(String toEmail, String title, String htmlContent) throws MessagingException
	{
		MimeMessage msg = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(msg, false, "utf-8");
		helper.setFrom(username);
		helper.setTo(toEmail);
		helper.setSubject(title);
		helper.setText(htmlContent, true);
		mailSender.send(msg);
	}

	/**
	 * 添加附件的email发送
	 * 
	 * @param toEmail
	 *            收件人地址
	 * @param title
	 *            邮件标题
	 * @param content
	 *            文本内容
	 * @param aboutFiles
	 *            附件信息 每个子项都是一个文件相关信息的map Map<String,String>: 1.filePath 2.fileName
	 * @throws Exception
	 *             异常
	 */
	public void sendAttachmentMail(String toEmail, String title, String content, List<Map<String, String>> aboutFiles)
			throws Exception
	{
		MimeMessage msg = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
		helper.setFrom(username);
		helper.setTo(toEmail);
		helper.setSubject(title);
		helper.setText(content);
		FileSystemResource resource = null;
		for (Map<String, String> file : aboutFiles)
		{
			resource = new FileSystemResource(file.get("filePath"));
			if (resource.exists())
			{// 是否存在资源
				File attachmentFile = resource.getFile();
				helper.addAttachment(file.get("fileName"), attachmentFile);
			}
		}
		mailSender.send(msg);
	}

}

测试

@Controller
public class IndexController
{	

	@Autowired
	private MailConfig mailConfig;	

	@RequestMapping("/text")
	public void text()
	{
			mailConfig.sendTextMail("xxxx@qq.com", "测试", "hahaha");
	}	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值