Spring Boot中使用JavaMailSender发送邮件
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EmailService {
private final JavaMailSender mailSender;
@Autowired
public EmailService(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendSimpleMail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
}
}
这段代码定义了一个EmailService
类,它使用JavaMailSender
来发送简单邮件。sendSimpleMail
方法接受收件人地址、邮件主题和邮件内容作为参数,创建一个SimpleMailMessage
对象,并设置这些参数,最后调用mailSender.send(message)
发送邮件。这个类可以在Spring Boot应用中注入并使用,用于发送各种通知或验证邮件等。
评论已关闭