使用SpringBoot实现电子邮件发送
1、在pox.xml中加入相关包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
如果使用的是spring项目,则换成springFramework对应的相关jar包即可
2、编写邮件发送逻辑
package com.example.service;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
/**
* 邮件发送业务逻辑
* @author yfly
* @date 2018年5月23日 上午11:28:48
*/
@Service
public class MailSenderService implements InitializingBean {
//加入日志
private static final Logger logger = LoggerFactory.getLogger(MailSenderService.class);
//使用该接口发送邮件
private JavaMailSenderImpl mailSender;
/**
* 发送邮件
* @param to
*/
public void sendMail(String to){
SimpleMailMessage mailMessage = new SimpleMailMessage();
//发送方邮箱
mailMessage.setFrom("yflyfox@163.com");
//接收方邮箱
mailMessage.setTo(to);
//发送的邮件主题
mailMessage.setSubject("spring 测试邮件发送");
//发送的邮件内容
mailMessage.setText("这是用Spring框架发送的邮件!,仅做测试使用");//后期通过值传递,注入
mailSender.send(mailMessage);
}
/**
* 配置邮件发送器
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
mailSender = new JavaMailSenderImpl();
//用户名
mailSender.setUsername("yflyfox@163.com");
//SMTP客户端的授权码(每个人这个密码不一样,密码与上面的username对应密码相同)
mailSender.setPassword("*******");
// 发件人邮箱的 SMTP 服务器地址
mailSender.setHost("smtp.163.com");
//邮件服务器监听的端口
mailSender.setPort(465);
//协议SMTP+SSL
mailSender.setProtocol("smtps");
mailSender.setDefaultEncoding("utf8");
Properties javaMailProperties = new Properties();
javaMailProperties.put("mail.smtp.ssl.enable", true);
mailSender.setJavaMailProperties(javaMailProperties);
}
}
3、编写电子邮件发送控制器
package com.example.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.service.MailSenderServic;
@Controller
public class MailSenderController {
private static final Logger logger = LoggerFactory.getLogger(MailSenderController.class);
@Autowired
MailSenderServic mailSender;
@RequestMapping(path = {"/mail"}, method = {RequestMethod.POST})
@ResponseBody
public String emailSend(){
try {
mailSender.sendMail("1456939892@qq.com");
logger.info("——————————>邮件发送成功");
return "邮件发送成功";
}catch (Exception e){
logger.error("邮件发送失败: " + e.getMessage());
return "邮件发送失败";
}
}
}
4、使用浏览器测试
localhost:8080/mail