pom.xml添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
添加aplication.yml
spring:
mail:
host: smtp.126.com
username: **@126.com
password: ***
服务
import com.ydp.ez.user.service.IEmailService;
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;
/**
* @Author: yedp
* @Date: 2019/11/22 9:24
* @Description:邮件服务
*/
@Service
public class EmailService implements IEmailService {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String sendUser;
@Override
public void sendEmail(String receiveEmail, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(sendUser);
message.setTo(receiveEmail);
message.setSubject(subject);
message.setText(content);
javaMailSender.send(message);
}
}
测试
@SpringBootTest()
public class EmailServiceTest {
@Autowired
IEmailService emailService;
@Test
public void sendMail() {
try {
String receiver = "**@qq.com";
emailService.sendEmail(receiver, "你好", "测试");
}catch (Exception e){
System.out.println(e);
}
}
}
网友评论