1. 添加maven依赖项:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId>
<version>${spring-boot-version}</version> </dependency>
2. 添加配置项 mail.properties
spring.mail.host=smtp.qq.com [email protected] spring.mail.password=授权码 spring.mail.port=465 spring.mail.protocol=smtps spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true spring.mail.default-encoding=UTF-8
3. 启动类扫描配置
@PropertySource(value = {"mail.properties"})
4. 发送邮件代码
import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.mail.internet.MimeMessage; @Slf4j @Servicepublic class MailService { @Autowired(required = false) private JavaMailSender mailSender; public boolean sendEmail(MailInfoBO mailInfo) { try { // 创建一个邮件消息 MimeMessage message = mailSender.createMimeMessage(); // 创建 MimeMessageHelper MimeMessageHelper helper = new MimeMessageHelper(message, false); // 发件人邮箱和名称 helper.setFrom("[email protected]", "测试"); // 收件人邮箱 helper.setTo(mailInfo.getToEmail()); // 邮件标题 helper.setSubject(mailInfo.getSubject()); // 邮件正文,第二个参数表示是否是HTML正文 helper.setText(mailInfo.getContent(), true); mailSender.send(message); return true; } catch (Exception e) { log.error("MailService error", e); } return false; } }
标签:QQ,spring,org,boot,springframework,mail,import,properties From: https://www.cnblogs.com/imgax/p/18260717