SPRING BOOT发送邮件验证码(Gmail邮箱)
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import javax.mail.internet.MimeMessage;
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
public void sendEmail(String to, String subject, String text) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom("your-email@gmail.com");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text, true);
mailSender.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
这段代码使用了Spring Boot的JavaMailSender来发送邮件。首先,它注入了JavaMailSender bean。然后,sendEmail方法被用来创建邮件,设置发送者和接收者,主题和邮件内容,并最终发送邮件。需要注意的是,你需要在application.properties或application.yml文件中配置你的Gmail邮箱的相关属性,以及你的Gmail密码或者专用的应用密码。
评论已关闭