SpringBoot整合Mail发送邮件

使用QQ邮箱,则需要先在QQ邮箱中开启POP3/SMTP服务。

如何设置?步骤如下:

打开qq邮箱 --> 设置 -->  账户 --> POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 --> 

POP3/SMTP服务 --> 开启

SpringBoot整合Mail发送邮件_第1张图片

SpringBoot整合Mail发送邮件_第2张图片

开启后得到授权码,这个授权码会配置到我们的配置文件中(提前复制保存一下):

SpringBoot整合Mail发送邮件_第3张图片

pom.xml 文件配置增加 mail 依赖:

// 省略......

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

application.yml 文件增加 mail 配置:

spring: 
    thymeleaf:
        cache : false
        prefix: classpath:/views/
        suffix: .html
        encoding: UTF-8
        content-type: text/html
        mode: LEGACYHTML5           
    devtools:
        restart:
            enabled : true
            exclud : WEB-INF/** 
    datasource:
        drive-class-name: com.mysql.jdbc.Driver
        username: root
        password: root
        url: jdbc:mysql://127.0.0.1:3306/xxx-db?characterEncoding=utf-8&useSSL=false
    jpa:
        show-sql: true  
    ### 发送邮件
    mail:
      ### QQ邮箱host: smtp.qq.com
      ### 163邮箱host: smtp.163.com
      host: smtp.qq.com
      protocol: smtp
      default-encoding: UTF-8
      ### QQ邮箱  
      username: [email protected]
      ### 授权码 
      password: pxxxxxxxxxxxxxxxxxxxe
      smtp:
        timeout: 10000
        auth: true
        starttls:
          enable: true
          required: true
      defaultEncoding: UTF-8          

测试类:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.test.context.junit4.SpringRunner;

import com.share.ShareApplication;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ShareApplication.class)
public class SendMailTest {

    @Autowired
    private JavaMailSender mailSender;
 
    @Value("${spring.mail.username}")
    private String senderFrom; 

	@Test
	public void test() {
	    SimpleMailMessage message = new SimpleMailMessage();
	    // 发送人邮箱
        message.setFrom(senderFrom);
        // 收件人邮箱,多个以逗号分隔
        message.setTo("[email protected]");
        // 邮件标题
        message.setSubject("SpringBoot整合Mail发送简单邮件");
        // 邮件内容
        message.setText("测试邮件...请勿回复!");
        // 发送
        mailSender.send(message);
		
	}
}

测试结果:

SpringBoot整合Mail发送邮件_第4张图片

 

你可能感兴趣的:(Java,Web)