一、打开网址start.spring.io
这个网站可以为你自动构建Spring Boot项目,如下图
你可以在上面选择需要构建的项目类型,所用程序语言,Sping Boot的版本以及所需要的依赖。然后点击Generate Project就可以保存项目源码。
二、然后打开IDE工具,这里我是用的是IDEA。
1.选择Import Project
2.选择项目路径,然后根据具体情况,更改配置,最后finish。
三、编辑代码
Spring Boot项目的结构此处不再赘述。
0.在pom.xml文件中添加邮件所需的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.properties文件中的邮件发送配置信息
#host:smtp."根据邮箱不同而变动".com
#username:这是你需要发送到邮箱A的邮箱地址
#password:这是该邮箱的授权码(并不是该邮箱A的登录密码)
#default-encoding:指定字符集编码,这个不用多说
spring.mail.host=smtp.163.com
[email protected]
spring.mail.password=cy199501
spring.mail.default-encoding=utf-8
service层:
1.文本邮件的发送
1.1 service层中的代码
package com.baidu.springbootmail.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class MailService {
@Value("${spring.mail.username}")
private String from;
@Autowired
private JavaMailSender mailSender;
public void sendSimpleMail(String to,String subject,String content){
/*
param to:这是要发送到的邮箱地址
param subject:这是邮件的主题
param content:这是邮件的正文
*/
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(content);
message.setFrom(from); //从哪里发送
mailSender.send(message);
}
}
1.2.进行测试
package com.baidu.springbootmail.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest{
@Resource
MailService mailService;
@Test
public void sendSimpleMailTest(){
mailService.sendSimpleMail("********@163.com","first mail","hello ones,this is my first mail");
}
}
结果如下:
未完待续。。。