共计 2297 个字符,预计需要花费 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);
}
}
`