Spring框架通过使用JavaMailSender接口为发送电子邮件提供了一个抽象,Spring Boot为它提供了自动配置以及一个启动模块。 其不同的属性配置可以查看MailProperties来解决。
2、Springboot对Email的自动配置
在容器中为我们添加了JavaMailSenderImpl的组件,该组件就是用来发送邮件的,还可以具体配置MailProperties来实现自定义
Host 主机名,username用户名,password密码(授权码)protocol 协议。以上属性配置的都是发送方的。
3、发送流程图
发送流程
4、基本的配置
登录邮箱选择设置,点击账户
选择开启POP3/SMTP
红框中为对应的授权码
5、代码实现
添加pom依赖<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.application.yml配置文件
spring:
mail:
host: smtp.qq.com
username: 你的qq邮箱地址password: 授权码
Host需要更新你不同的邮箱服务器换成不同的地址如163(smtp.163.com)
3.发送代码
@Autowired
private JavaMailSenderImpl javaMailSender;//简单邮件发送@Testvoid contextLoads() {SimpleMailMessage simpleMailMessage = new SimpleMailMessage();simpleMailMessage.setSubject("邮件标题");simpleMailMessage.setTo("换成你需要接收人的邮箱地址");simpleMailMessage.setText("具体内容");simpleMailMessage.setFrom("换成你的邮箱地址");javaMailSender.send(simpleMailMessage);}//复杂邮件的发送@Testvoid contextLoadsFz() throws MessagingException {//创建一个复杂的消息邮件MimeMessage mimeMessage = javaMailSender.createMimeMessage();MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
//邮件设置
mimeMessageHelper.setSubject("邮件标题");// mimeMessageHelper.setText("具体内容"); //发送普通文本mimeMessageHelper.setText("<p>具体内容</p>",true); //发送html的文本mimeMessageHelper.setTo("换成你需要接收人的邮箱地址");mimeMessageHelper.setFrom("换成你的邮箱地址");//发送附件mimeMessageHelper.addAttachment("1.jpg",new File("F:\\img\\1.jpg"));javaMailSender.send(mimeMessage);}
以上为发送邮件的原理和测试类代码。正式中可以将发送内容定义为实体类直接传递发送。或者将以上发送的代码封装成工具类直接使用
@Controller public class EmailController { @Autowired private EmailService emailService; @Autowired private TemplateEngine templateEngine; @Autowired private DynamicSchedulerService dynamicSchedulerService; String regex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$"; Pattern pattern = Pattern.compile(regex); String fileName = ""; String dirPath = ""; String imgName = ""; String imgPath = ""; String timehour=""; String timeminute=""; String emailusername=""; String emailtitle=""; String emailtext=""; String cron=""; @ResponseBody @PostMapping("/emailindex/emailText") public String emailText(@RequestParam("emailname") String emailname, @RequestParam("title") String title, @RequestParam("text") String text) { Matcher matcher = pattern.matcher(emailname); if (emailname.equals("")) { return "邮箱为空,请输入邮箱"; } else { if (matcher.matches()) { if (text.equals("")) { return "内容为空,请输入内容"; } else { if (text.length() <= 100) { // Call the sendSimpleEmail method from emailService boolean isEmailSent = emailService.sendSimpleEmail(emailname, title, text); if (isEmailSent) { // Return a success message and navigate back to the previous two pages using JavaScript return "<script>alert('纯文本邮件发送成功');window.history.go(-2);</script>";//返回两页 } else { // Return an error message and navigate back using JavaScript return "<script>alert('纯文本邮件发送失败');window.history.back();</script>"; } } else { return "文本内容大于100字,当前字数:" + text.length() + "字"; } } } else { return "邮箱格式不正确,请重新输入"; } } } @ResponseBody @PostMapping("/emailindex/emailAnnex") public String emailAnnex(@RequestParam("file") MultipartFile[] fileUpload, @RequestParam("emailname") String emailname, @RequestParam("title") String title) { String fileName = ""; String dirPath = ""; for (MultipartFile file : fileUpload) { fileName = file.getOriginalFilename(); dirPath = "D:\\zht\\"; File filePath = new File(dirPath); if (!filePath.exists()) { filePath.mkdirs(); } try { file.transferTo(new File(dirPath + fileName)); } catch (Exception e) { e.printStackTrace(); // Handle upload failure } } Matcher matcher = pattern.matcher(emailname); if (emailname.equals("")) { return "邮箱为空,请输入邮箱"; } else { if (matcher.matches()) { if (fileName.equals("")) { return "未添加附件"; } else { // Call the sendComplexEmail method from emailService emailService.sendComplexEmail(emailname, title, "", dirPath + fileName); // Return a success message and navigate back to the previous two pages using JavaScript return "<script>alert('附件邮件发送成功');window.history.go(-2);</script>"; } } else { return "邮箱格式不正确,请重新输入"; } } } @ResponseBody @PostMapping("/emailindex/emailImg") public String emailImg(@RequestParam("img") MultipartFile[] fileUpload, @RequestParam("emailname") String emailname, @RequestParam("title") String title) { String imgName = ""; String imgPath = ""; for (MultipartFile file : fileUpload) { imgName = file.getOriginalFilename(); imgPath = "D:\\zht\\"; File filePath = new File(imgPath); if (!filePath.exists()) { filePath.mkdirs(); } try { file.transferTo(new File(imgPath + imgName)); } catch (Exception e) { e.printStackTrace(); // Handle upload failure } } Matcher matcher = pattern.matcher(emailname); String suffix = imgName.substring(imgName.lastIndexOf(".") + 1); if (emailname.equals("")) { return "邮箱为空,请输入邮箱"; } else { if (matcher.matches()) { if (imgName.equals("")) { return "未添加图片"; } else { if (suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("png") || suffix.equalsIgnoreCase("bmp") || suffix.equalsIgnoreCase("jpeg")) { StringBuilder text = new StringBuilder(); text.append("<html><head></head>"); text.append("<body>"); String rscId = "img001"; text.append("<img src='cid:" + rscId + "'/></body>"); text.append("</html>"); // Call the sendComplexEmail method from emailService emailService.sendComplexEmail(emailname, title, text.toString(), rscId, imgPath + imgName); // Return a success message and navigate back to the previous two pages using JavaScript return "<script>alert('图片邮件发送成功');window.history.go(-2);</script>"; } else { return "图片格式有误,请重新添加"; } } } else { return "邮箱格式不正确,请重新输入"; } } } @ResponseBody @PostMapping("/emailindex/emailTemplate") public String emailTemplate(@RequestParam("emailname") String emailname, @RequestParam("title") String title, @RequestParam("name") String name, @RequestParam("yanzhengma") String yzm) { Matcher matcher = pattern.matcher(emailname); if (emailname.equals("")) { return "邮箱为空,请输入邮箱"; } else { if (matcher.matches()) { if (name.equals("")) { return "请输入用户名"; } else { Context context = new Context(); context.setVariable("username", name); context.setVariable("code", yzm); String emailContent = templateEngine.process("email/emailverify", context); // Call the sendTemplateEmail method from emailService emailService.sendTemplateEmail(emailname, title, emailContent); // Return a success message and navigate back to the previous two pages using JavaScript return "<script>alert('模板邮件发送成功');window.history.go(-2);</script>"; } } else { return "邮箱格式不正确,请重新输入"; } } } @ResponseBody @PostMapping("/emailindex/emailTiming") public String emailTiming(@RequestParam("emailname") String emailname, @RequestParam("title") String title, @RequestParam("text") String text, @RequestParam("week") String day, @RequestParam("time") String time) { Matcher matcher = pattern.matcher(emailname); // Global variable to store the email title emailtitle = title; if (emailname.equals("")) { return "邮箱为空,请输入邮箱"; } else { if (matcher.matches()) { // Global variable to store the email address emailusername = emailname; if (text.equals("")) { return "内容为空,请输入内容"; } else { if (text.length() <= 100) { // Global variable to store the email text emailtext = text; if (day.equals("0")) { return "请选择你要设置的星期"; } else { if (time.equals("")) { return "请选择你要设置的时间"; } else { // Global variables to store hour and minute timehour = time.substring(0, time.lastIndexOf(":")); timeminute = time.substring(time.lastIndexOf(":") + 1); // Get the new cron expression cron = "0 " + timeminute + " " + timehour + " * * " + day; // Call the startScheduledTask method from dynamicSchedulerService dynamicSchedulerService.startScheduledTask(cron); // Return a success message and navigate back to the previous two pages using JavaScript return "<script>alert('设置定时任务完成');window.history.go(-2);</script>"; } } } else { return "文本内容大于100字,当前字数:" + text.length() + "字"; } } } else { return "邮箱格式不正确,请重新输入"; } } } }
@Service public class EmailService { @Autowired private JavaMailSenderImpl mailSender; @Value("${spring.mail.username}") private String from; public boolean sendSimpleEmail(String to, String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(text); try { mailSender.send(message); return true; } catch (MailException e) { e.printStackTrace(); return false; } } public void sendComplexEmail(String to, String subject, String text, String filePath) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text, true); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); helper.addAttachment(MimeUtility.encodeText(fileName, "GBK", "B"), file); mailSender.send(message); } catch (MessagingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public void sendComplexEmail(String to, String subject, String text, String rscId, String rscPath) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text, true); FileSystemResource res = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, res); mailSender.send(message); } catch (MessagingException e) { e.printStackTrace(); } } public void sendTemplateEmail(String to, String subject, String content) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); mailSender.send(message); } catch (MessagingException e) { e.printStackTrace(); } } public void sendComplexEmail(String to, String subject, String text, String filePath, String rscId, String rscPath) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text, true); FileSystemResource res = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, res); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); helper.addAttachment(MimeUtility.encodeText(fileName, "GBK", "B"), file); mailSender.send(message); } catch (MessagingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } }
<style> form { background: #9ceeda; display: flex; flex-direction: column; align-items: flex-start; margin-bottom: 20px; } label { display: block; margin-bottom: 10px; font-weight: bold; font-size: 16px; } input[type="text"], textarea { width: 100%; padding: 10px; border: 1px solid #f32626; border-radius: 3px; box-sizing: border-box; margin-bottom: 10px; font-size: 14px; } </style> </head>