Spring Boot 整合 spring-boot-starter-mail 实现邮件发送和账户激活
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
@Service
public class MailService {
private final JavaMailSender mailSender;
private final SimpleMailMessage simpleMailMessage;
@Autowired
public MailService(JavaMailSender mailSender) {
this.mailSender = mailSender;
this.simpleMailMessage = new SimpleMailMessage();
// 设置邮件的基本属性
simpleMailMessage.setFrom("noreply@yourdomain.com");
simpleMailMessage.setSubject("Account Activation");
}
public void sendMail(String email, String activationLink) {
simpleMailMessage.setTo(email);
simpleMailMessage.setText("Hi, \n\n"
+ "Please click on the below link to activate your account:\n"
+ activationLink + "\n\n"
+ "Regards, \n"
+ "Your Team");
mailSender.send(simpleMailMessage);
}
}
这段代码定义了一个MailService类,它使用了Spring Boot提供的spring-boot-starter-mail依赖来发送邮件。在发送邮件时,它设置了邮件的基本属性,如发件人、主题和邮件内容。然后,它提供了一个sendMail方法来发送邮件给用户,其中包含了用户的激活链接。这个类可以被注入到需要发送邮件的服务中,例如用户服务,当创建新用户或需要发送账户激活邮件时使用。
评论已关闭