springBoot 如何发送邮件实例源码

springBoot 如何发送邮件
1、配置pom文件

  
			org.springframework.boot
			spring-boot-starter-mail
	

2、设置邮件服务器
打开邮箱,【设置】–>【账户】,找到(POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务),开启前两项服务,并获取授权码
3、在application.properties配置文件进行属性配置

     spring.mail.username=发送人地址
	 spring.mail.password=邮件授权码
	 spring.mail.host=smtp.qq.com 
	 spring.mail.properties.mail.smtp.ssl.enable=true

4、Java 代码

package com.smtp.email;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;

import javax.mail.internet.MimeMessage;
import java.io.File;

@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailApplicationTests {
	@Autowired
	JavaMailSender mailSender;
	@Test
	public void contextLoads() {
	}
	@Test
	public void testEmail() throws Exception{
		MimeMessage mimeMessage = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
		helper.setTo("收件人地址");
		helper.setText("

java 发送邮件测试!

",true);//邮件内容,true:可以识别html标签 helper.setSubject("通知");//邮件主题 helper.setFrom("发件人地址"); helper.addAttachment("附件名称",new File("附件地址")); helper.addAttachment("附件名称",new File("附件地址")); mailSender.send(mimeMessage); } }

你可能感兴趣的:(springboot,邮件)