Spring Boot邮件REST API无法访问,求正确调用方案
开发一个带REST API的Spring Boot应用,该API可通过传入包含邮箱凭证的JSON发送邮件,应用不涉及数据库操作。已编写MailController、MailPojo及MailServiceImpl实现邮件发送逻辑,启动后控制台显示Tomcat在8080端口启动,上下文路径为空。但使用Postman调用http://localhost:8080/mailsend/mailService/sendMail时无法访问API,请问如何成功调用该API?
MailController
@RestController @RequestMapping("/mailService") public class MailController{ @Autowired private MailService mailService; @PostMapping("/sendMail") public ResponseEntity<Long> sendMail(@RequestBody MailPojo pojo){ System.out.println("POST Request ...."); MailResponse resp = mailService.sendMail(pojo); return new ResponseEntity(resp, HttpStatus.CREATED); } }
MailPojo
public class MailPojo { private String smtpServer; private String userName; private String password; private String smtpPort; private String emailFrom; private String emailTo; private String emailCC; private String emailSubject; private String emailText; ... ...... }
MailServiceImpl
@Service @Slf4j public class MailServiceImpl implements MailService { @Override public MailResponse sendMail(MailPojo pojo) { String srvrResp = ""; String retn = ""; String SMTP_SERVER = pojo.getSmtpServer(); final String USERNAME = pojo.getUserName(); final String PASSWORD = pojo.getPassword(); String TLS = "Y"; String smtpPort = pojo.getSmtpPort(); String EMAIL_FROM = pojo.getEmailFrom(); String EMAIL_TO = pojo.getEmailTo(); String EMAIL_CC = pojo.getEmailCC(); String EMAIL_SUBJECT = pojo.getEmailSubject(); String EMAIL_TEXT = pojo.getEmailText(); Properties prop = System.getProperties(); prop.put("mail.smtp.host", SMTP_SERVER); // optional, defined in SMTPTransport prop.put("mail.smtp.auth", "true"); prop.put("mail.smtp.port", smtpPort); // default port 25 (TLS) prop.put("mail.smtp.socketFactory.port", "465"); //SSL Port prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); //SSL Factory Class Authenticator auth = new Authenticator() { //override the getPasswordAuthentication method protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(USERNAME, PASSWORD); } }; Session session = Session.getInstance(prop, auth); System.out.println("Session created"); Message msg = new MimeMessage(session); try { ... .... ...... t.sendMessage(msg, msg.getAllRecipients()); System.out.println("Response: " + t.getLastServerResponse()); srvrResp = t.getLastServerResponse(); retn ="SUCCESS"; t.close(); } catch (MessagingException e) { retn = "FAILED"; e.printStackTrace(); } ..... ........ return respObj; } }
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.7.12) 2023-06-11 22:53:10.535 INFO 3048 --- [ restartedMain] in.issac.mailsend.MailsendApplication : Starting MailsendApplication using Java 17.0.7 on DESKTOP-QU763SD with PID 3048 (F:\STS_Workspace\mailsend\target\classes started by Jayanta Pramanik in F:\STS_Workspace\mailsend) 2023-06-11 22:53:10.551 INFO 3048 --- [ restartedMain] in.issac.mailsend.MailsendApplication : No active profile set, falling back to 1 default profile: "default" 2023-06-11 22:53:10.680 INFO 3048 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable 2023-06-11 22:53:10.680 INFO 3048 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG' 2023-06-11 22:53:12.816 INFO 3048 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2023-06-11 22:53:12.838 INFO 3048 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2023-06-11 22:53:12.839 INFO 3048 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.75] 2023-06-11 22:53:12.969 INFO 3048 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2023-06-11 22:53:12.971 INFO 3048 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2289 ms 2023-06-11 22:53:13.927 INFO 3048 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 2023-06-11 22:53:14.017 INFO 3048 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2023-06-11 22:53:14.055 INFO 3048 --- [ restartedMain] in.issac.mailsend.MailsendApplication : Started MailsendApplication in 4.256 seconds (JVM running for 5.13)
1. 修正请求URL
从启动日志可知,应用的上下文路径为空(context path ''),而MailController的请求映射是/mailService,接口的POST映射是/sendMail,因此正确的请求URL应该是:http://localhost:8080/mailService/sendMail
当前调用的URL多了/mailsend(项目文件夹名称),但Spring Boot并未将其设为上下文路径,因此需要去掉。
2. 确保请求方式与参数正确
- 请求方式必须为POST,在Postman中选择POST方法。
- 请求体必须是符合MailPojo结构的JSON数据,同时要将
Content-Type设置为application/json。示例JSON如下:
{ "smtpServer": "smtp.example.com", "userName": "your-email@example.com", "password": "your-password", "smtpPort": "465", "emailFrom": "sender@example.com", "emailTo": "recipient@example.com", "emailCC": "cc-recipient@example.com", "emailSubject": "Test Email", "emailText": "This is a test email content." }
3. 验证Controller是否被Spring扫描
检查启动类MailsendApplication的包路径(in.issac.mailsend),确保MailController所在的包是其子包(比如in.issac.mailsend.controller)。Spring Boot默认会扫描启动类所在包及其子包下的组件,如果Controller在其他包,需要在启动类上添加@ComponentScan(basePackages = "your.controller.package")指定扫描路径。
4. 排查拦截/安全配置
如果项目中引入了Spring Security或自定义拦截器,需要确保/mailService/sendMail接口被允许访问,避免被拦截。
5. 开启日志排查问题
在application.properties或application.yml中添加配置,开启Web层的DEBUG日志,查看请求是否到达Spring框架,以及是否存在映射错误:
logging.level.web=DEBUG
启动应用后重新调用接口,查看控制台日志,确认请求的URL、方法是否与Controller的映射匹配。
内容的提问来源于stack exchange,提问作者Jayanta Pramanik

