![cc93171de19cf92a52fb882f9588c3cb.png](https://i-blog.csdnimg.cn/blog_migrate/18bdf45682332d3dea3a8ab7264d7eff.jpeg)
通过使用Spring Boot RESTful Web服务,可以发送包含Gmail传输层安全性的电子邮件。 在本章中,详细了解如何使用此功能。
首先,需要在构建配置文件中添加Spring Boot Starter Mail依赖项。
Maven用户可以将以下依赖项添加到pom.xml 文件中。
org.springframework.boot
spring-boot-starter-mail
Gradle用户可以在build.gradle 文件中添加以下依赖项。
compile('org.springframework.boot:spring-boot-starter-mail')
主 Spring Boot 应用程序类文件的代码如下 -
package com.felix.emailapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EmailappApplication {
public static void main(String[] args) {
SpringApplication.run(EmailappApplication.class, args);
}
}
可以编写一个简单的Rest API,以便在Rest Controller类文件中发送到电子邮件,如图所示。
package com.felix.emailapp;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmailController {
@RequestMapping(value = "/sendemail")
public String sendEmail() {
return "Email sent successfully";
}
}
编写一个方法来发送带有附件的电子邮件。 定义mail.smtp属性并使用PasswordAuthentication。
private void sendmail() throws AddressException, MessagingException, IOException {
Properties props = new Properties();
props.put("mail.smtp.auth