SpringBoot整合邮件发送功能
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
邮箱配置
发送简单邮件
@Service
public class MailService {
@Resource
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String fromEmail;
/**
* 发送文本邮件
*/
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(fromEmail);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
}
sendSimpleMail的三个参数依次是:邮件的发送目标,邮件的标题,邮件的内容。
test测试代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {
@Autowired
MailService mailService;
@Test
public void sendSimpleMail() {
mailService.sendSimpleMail("951687336@qq.com",
"普通文本邮件",
"普通文本邮件内容测试");
}
}
controller中代码测试
@Controller
public class WireTest {
@Autowired
private MailService mailService;
@RequestMapping("test")
@ResponseBody
public String emailTest(){
mailService.sendSimpleMail("951687336@qq.com",
"普通文本邮件",
"普通文本邮件内容测试");
return "success";
}
}
发送html邮件
发送普通的文本文件邮件,使用的是SimpleMailMessage
发送的正文是HTML的邮件,使用的是MimeMessage
/**
* 发送html邮件
*/
public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
//注意这里使用的是MimeMessage
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(fromEmail);
helper.setTo(to);
helper.setSubject(subject);
//第二个参数是否是html,true表示发送的邮件正文是html文本
helper.setText(content, true);
mailSender.send(message);
}
测试
@Test
public void sendHtmlMail() throws MessagingException {
mailService.sendHtmlMail("431899405@qq.com","一封html测试邮件","<body style="text-align: center;margin-left: auto;margin-right: auto;">
"
+ " <div id="welcome" style="text-align: center;position: absolute;" >
"
+" <h3>"一封html测试邮件"</h3>
"
+" <span>http://www.zimug.com</span>"
+ " <div style="text-align: center; padding: 10px"><a style="text-decoration: none;" href="https://zimug.com" target="_bank" >"
+ " <strong>我很用心,希望你有所收获</strong></a></div>
"
+ " </div>
" + "</body>");
}