springboot(七):发送邮件

1. 引入依赖

<!-- 发送邮件 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2. application.yum添加配置

需要开启客户端授权,否则发送失败,SMTPAuthenticationError  ----------  550    User has no permission

#发送邮件
spring:
  mail:
    host: smtp.163.com
    # 在163.com注册的用户名,注意这里不需要@163.com后缀
    username: ynzz12***
    # 在163.com配置的客户端授权密码,进入163邮箱-设置-客户端授权密码-开启
    password: xxxxxx

3. 发送简单邮件和带附件的邮件

package com.szl.controller;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.szl.vo.ResultVo;

/**
 * @author sunzl
 * @date 2018年11月25日
 * 
 * 发送邮件
 * 
 */
@RestController
@RequestMapping("/mail")
public class MailController {
	
	@Autowired
	private JavaMailSender javaMailSender;

	/**
	 * 发送简单邮件
	 * @return
	 */
	@RequestMapping("/sendMail")
	public ResultVo sendMail(){
		ResultVo resultVo = new ResultVo();
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom("ynzz12***@163.com");
		message.setTo("sunn***@163.com");
		message.setSubject("主题");
		message.setText("发送的内容");
		javaMailSender.send(message);
		resultVo.setCode("0");
		resultVo.setMsg("成功");
		resultVo.setData("");
		return resultVo;
	}
	
	/**
	 * 发送带有附件的邮件
	 * @return
	 * @throws MessagingException 
	 */
	@RequestMapping("/sendMailAttachment")
	public ResultVo sendMailAttachment() throws MessagingException{
		ResultVo resultVo = new ResultVo();
		MimeMessage mimeMessage = javaMailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
		helper.setFrom("ynzz123**@163.com");
		helper.setTo("sunny***@163.com");
		helper.setSubject("主题");
		helper.setText("发送的内容");
		// src/main/resource下面的文件
		ClassPathResource resource = new ClassPathResource("/application.yml");
		helper.addAttachment("我是附件", resource);
		javaMailSender.send(mimeMessage);
		resultVo.setCode("0");
		resultVo.setMsg("成功");
		return resultVo;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值