使用SpringBoot发送Gmail和QQ邮箱

it2024-11-08  6

使用SpringBoot发送Gmail和QQ邮箱

概述

如何使用SpringBoot发送Gmail、QQ邮箱,发送文本、附件和模板。

代码如下:

DemoApplication.java

package com.example.sendmail.demo; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Controller class MainController{ @Value("${spring.mail.username}") private String username; /** * 发送邮件页面 * @return */ @GetMapping(value = {"/","/send/form"}) public String form(Model model){ model.addAttribute("from",username); return "send-form"; } } }

MailController.java

package com.example.sendmail.demo; import lombok.RequiredArgsConstructor; import lombok.extern.log4j.Log4j2; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.mail.MessagingException; @Log4j2 @RestController @RequiredArgsConstructor @RequestMapping("/send") public class MailController { private final MailService mailService; /** * 发送文本 * @param mailBody * @return */ @PostMapping("/text") public Boolean text(@RequestBody MailBody mailBody){ return mailService.sendText(mailBody); } /** * 发送附件 * @param mailBody * @param file * @return * @throws MessagingException */ @PostMapping("/attach") public Boolean attach(@RequestParam("mailBody") MailBody mailBody,@RequestParam("file") MultipartFile file) throws MessagingException { mailBody.setFile(file); log.info("file name:{}",file.getOriginalFilename()); log.info("mailBody:{},",mailBody.toString()); return mailService.sendAttachment(mailBody); } /** * 发送模板 * @param mailBody * @return * @throws MessagingException */ @PostMapping("/template") public boolean template(@RequestBody MailBody mailBody) throws MessagingException { return mailService.sendTemplate(mailBody); } }

 

最新回复(0)