1 在properties.yml文件中配置邮箱信息
email:
password: **** #登录邮箱的密码
authorcode: ****** #邮箱第三方登录的授权码
form: 15239491151@163.com ***** 邮件的发送方
2 创建邮件发送的Service
public interface EmailTestService {
void sendMail(String to,String subject,String content);
}
3 实现邮箱的发送接口
@Service
public class EmailTestServiceImpl implements EmailTestService {
@Value("${email.password}")
private String password1;
@Value("${email.authorcode}")
private String password2;
@Value("${email.form}")
private String form;
@Override
public void sendMail(String to, String subject, String content) {
try{
Properties properties = new Properties();
//邮箱登录信息 使用stmp登录, 获取邮箱的连接Session
properties.setProperty("mail.smtp.host","smtp.163.com");
properties.setProperty("mail.smtp.username","15239491151@163.com");
properties.setProperty("mail.smtp.password",password1);
properties.setProperty("mail.smtp.defaultEncoding","UTF-8");
//465端口用于发布到阿里云服务器。如果使用25端口会失败,阿里云服务器默认禁用了25端口
properties.setProperty("mail.smtp.port","465");
properties.setProperty("mail.smtp.auth","true");
properties.setProperty("mail.smtp.ssl.enable","true");
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("15239491151",password2);
}
});
//通过会话,得到一个邮箱,用于发送
MimeMessage mimeMessage = new MimeMessage(session);
//发送方
mimeMessage.setFrom(new InternetAddress(form));
//接受方
mimeMessage.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to,false));
//邮件主题
mimeMessage.setSubject(subject);
//邮件内容
Multipart multipart = new MimeMultipart();
//创建内容
BodyPart html = new MimeBodyPart();
html.setContent(content,"text/html;charset=utf-8");
multipart.addBodyPart(html);
//设置邮箱内容
mimeMessage.setContent(multipart);
//发送
Transport.send(mimeMessage);
System.out.println("邮件以及发送");
}
catch (Exception e)
{
System.out.println("邮件发送异常");
e.printStackTrace();
}
}
}
编写测试类
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {Application.class})
public class EmailTest {
@Autowired
private EmailTestService emailTestService;
@Test
public void sendMail()
{
emailTestService.sendMail("1901264371@qq.com","emailTest","hello spring email");
}
}