在Spring Boot中,我们可以使用JavaMailSender接口来发送邮件。以下是一个简单的示例,展示了如何在Spring Boot应用程序中设置和使用邮件发送功能。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.properties:
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=your_email@example.com
spring.mail.password=your_email_password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
application.yml:
spring:
mail:
host: smtp.example.com
port: 587
username: your_email@example.com
password: your_email_password
properties:
mail:
smtp:
auth: true
starttls:
enable: true
请确保将上述配置中的值替换为您的SMTP服务器信息。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class EmailService {
@Autowired
private JavaMailSender javaMailSender;
public void sendSimpleMessage(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
javaMailSender.send(message);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmailController {
@Autowired
private EmailService emailService;
@GetMapping("/sendEmail")
public String sendEmail() {
emailService.sendSimpleMessage("recipient@example.com", "Test Subject", "Test email body");
return "Email sent!";
}
}
现在,当您访问/sendEmail
端点时,应用程序将发送一封包含指定收件人、主题和正文的电子邮件。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。