直接上代码了,简单粗暴(太简单,不要兴奋)
一、pom文件
<!-- 邮件发送 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
二、application.yml文件
mail: host: smtp.163.com username: 15136358062@163.com password: ***** default-encoding: UTF-8
注意事项:
用户名:填写你自己的邮箱
授权密码:打开你的邮箱
三、进行发送
1,建立一个类 SendByEmailTools,应该是继承一个service(我这儿省略了,直接写的实现类,没有写接口)
@Service("serdbyemail") public class SendByEmailTools { @Autowired JavaMailSender jms; public String send(String sender,String receiver,String title,String text){ //建立邮件消息 SimpleMailMessage mainMessage = new SimpleMailMessage(); //发送者 System.out.println("发送者 ------------------"); mainMessage.setFrom(sender); System.out.println("接收者 ------------------"); //接收者 mainMessage.setTo(receiver); //发送的标题 mainMessage.setSubject(title); //发送的内容 mainMessage.setText(text); jms.send(mainMessage); return "1"; } }
2,建立controller类,SendByEmailController
/** * */ package com.yuyi.mcb.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.yuyi.full.handler.exception.ResultBO; import org.yuyi.full.handler.exception.ResultTool; import com.yuyi.mcb.tool.SendByEmailTools; /** * @author mcb * 2018年5月4日 下午3:52:30 * */ @RestController public class SendByEmailController { @Autowired @Qualifier("serdbyemail") private SendByEmailTools service; @GetMapping("/send") public String send(){ String sender=""; //这个是发送人的邮箱 String receiver=""; //这个是接受人的邮箱 String title="约翰福音"; //标题 String text="【约3:16】“ 神爱世人,甚至将他的独生子赐给他们,叫一切信他的,不至灭亡,反得永生。"; String result=service.send(sender, receiver, title, text); return result; } }
运行一下,是不是发现收到邮件了呢?