spring boot 使用邮箱

  作者:记性不好的阁主

0、准备


导入邮箱启动器依赖


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>



登录qq邮箱


1) 找到设置






2) 找到账户




3) 开启第三方控制发送邮箱


按照如图配置





1、配置application.properties


spring.mail.username=1051513344@qq.com
spring.mail.password=***
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true


其中spring.mail.password为qq邮箱的授权码



qq邮箱生成授权码:





2、测试发送邮箱


简单文本邮箱


package com.laoxu.springboot;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

@SpringBootTest
class SpringBoot05MailApplicationTests {


@Autowired
JavaMailSenderImpl mailSender;


@Test
void contextLoads() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setSubject("通知-今晚开会");
simpleMailMessage.setText("今晚19:30开会");
simpleMailMessage.setTo("2448893124@qq.com");
simpleMailMessage.setFrom("1051513344@qq.com");
mailSender.send(simpleMailMessage);
}

}



相关说明:


subject 标题

text 内容

to 收件人

from 发件人


运行后即可发送到目标邮箱


复杂邮箱


package com.laoxu.springboot;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

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

@SpringBootTest
class SpringBoot05MailApplicationTests {


@Autowired
JavaMailSenderImpl mailSender;


@Test
void test02() throws Exception{
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("通知");
helper.setText("开会-今晚<b style='color: red'>7:30</b>",true);
helper.setTo("2448893124@qq.com");
helper.setFrom("1051513344@qq.com");

//上传文件
helper.addAttachment("1.jpg",new File("C:\\Users\\xushunjie\\Desktop\\1.jpg"));
helper.addAttachment("2.jpg",new File("C:\\Users\\xushunjie\\Desktop\\2.jpg"));

mailSender.send(mimeMessage);
}

}


相关说明:


helper.setText("内容","是否生成html格式")

addAttachment   添加附件



相关推荐

评论 抢沙发

表情

分类选择