以下是使用 Spring Boot 实现发送 QQ 邮件的详细代码和步骤:

  1. 引入依赖

pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
  1. 配置邮件服务器

application.properties 文件中添加以下配置:

spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=your_qq_email@qq.com
spring.mail.password=your_qq_email_password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enable=true

注意:

  • your_qq_email@qq.com 替换为你的 QQ 邮箱地址。
  • your_qq_email_password 替换为你的 QQ 邮箱密码。
  • 在发送邮件之前,请确保你已经开启了 QQ 邮箱的 SMTP 服务。
  1. 编写邮件发送工具类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

@Component
public class MailUtil {

    @Autowired
    private JavaMailSender mailSender;

    public void sendMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom('your_qq_email@qq.com');
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }
}
  1. 在业务代码中使用邮件发送工具类发送邮件
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MailController {

    @Autowired
    private MailUtil mailUtil;

    @GetMapping('/sendMail')
    public String sendMail() {
        String to = 'recipient_email@example.com';
        String subject = 'Spring Boot Email';
        String content = 'This is a test email sent from Spring Boot.';
        mailUtil.sendMail(to, subject, content);
        return 'Mail sent successfully';
    }
}

注意:

  • recipient_email@example.com 替换为你要发送的邮件地址。
  • Spring Boot EmailThis is a test email sent from Spring Boot. 分别替换为你的邮件主题和内容。

以上步骤完成后,你就可以成功使用 Spring Boot 发送 QQ 邮件了。

其他注意事项:

  • 为了安全起见,建议不要将 QQ 邮箱密码直接写在代码中,可以使用环境变量或配置文件进行配置。
  • 可以根据需要使用 MimeMessageHelper 类发送更复杂的邮件,例如包含附件或HTML内容的邮件。
  • 如果遇到发送邮件失败的问题,请检查你的 QQ 邮箱 SMTP 服务是否开启,以及你的代码配置是否正确。
SpringBoot 实现发送 QQ 邮件 - 详细代码和配置

原文地址: https://www.cveoy.top/t/topic/oimf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录