【Java】Spring Boot使用 Email 传邮件 (上手图解)
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import javax.mail.MessagingException;
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, "UTF-8");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text, true);
mailSender.send(message);
System.out.println("邮件发送成功");
} catch (MessagingException e) {
e.printStackTrace();
System.out.println("邮件发送失败");
}
}
}
这段代码演示了如何在Spring Boot应用程序中使用JavaMailSender发送文本邮件。首先,我们注入了JavaMailSender bean。然后,我们创建了一个MimeMessage,并使用MimeMessageHelper来设置收件人、主题和邮件内容。最后,我们调用mailSender.send()方法来发送邮件。如果发送成功,会打印出"邮件发送成功",如果发送失败,则会捕获异常并打印错误信息"邮件发送失败"。
评论已关闭