获取邮箱授权码
打开POP3/SMTP服务
复制授权码
pom.xml导入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
修改application.yml
spring:mail:host: smtp.163.comusername: 邮箱名password: 授权码port: 465protocol: smtpdefault-encoding: UTF-8properties:mail:smtp:ssl:enable: truesocketFactory:port: 465class: javax.net.ssl.SSLSocketFactorydebug: true
调用JavaMailSender发送邮件
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;import java.util.Date;
import java.util.List;@Service
public class MailServiceImpl {private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl .class);/*** 注入邮件工具类*/@Autowired(required = false)private JavaMailSender javaMailSender;@Value("${spring.mail.username}")private String sendMailer; // 发送者邮箱/*** receivers: 接收者邮箱*/@Overridepublic void sendTextMailMessage(List<String> receivers, String subject, String content) {try {logger.info("发送:{} -> {}", sendMailer, receivers);MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);mimeMessageHelper.setFrom(sendMailer);mimeMessageHelper.setTo(receivers.toArray(String[]::new));//邮件主题mimeMessageHelper.setSubject(subject);//邮件内容mimeMessageHelper.setText(content);//邮件发送时间mimeMessageHelper.setSentDate(new Date());//发送邮件javaMailSender.send(mimeMessageHelper.getMimeMessage());logger.info("发送邮件成功:{} -> {}", sendMailer, receivers);} catch (Exception e) {logger.error("发送邮件失败:{} -> {}", sendMailer, receivers);logger.error("发送邮件失败", e);throw new BusinessException(LarkPassRestResultCode.ERROR, "发送邮件失败");}}
}