首页 > 其他分享 >Springboot 自动发送邮件

Springboot 自动发送邮件

时间:2023-11-23 17:11:46浏览次数:35  
标签:Springboot cc param 发送 import mail 邮件 String

   完成Springboot配置发件邮箱,自动给其他邮箱发送邮件功能

一、创建springboot基础项目,引入依赖

<!-- Spring Boot 邮件依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- Spring Boot 模板依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

二、配置文件添加必要的配置:

#qq邮箱为例
spring.mail.host=smtp.qq.com

spring.mail.port=465

[email protected]

spring.mail.password=XXXXXX  #不是邮件密码而是授权码(邮箱设置里获取)

spring.mail.protocol=smtp

spring.mail.test-connection=true

spring.mail.default-encoding=UTF-8

spring.mail.properties.mail.smtp.auth=true

spring.mail.properties.mail.smtp.starttls.enable=true

spring.mail.properties.mail.smtp.starttls.required=true

spring.mail.properties.mail.smtp.ssl.enable=true

spring.mail.properties.mail.display.sendmail=spring-boot-demo

 

   三、工程结构

 

四、MailService接口
package com.example.mail.demo;

import javax.mail.MessagingException;

public interface MailService {
    /**
     * 发送文本邮件
     *
     * @param to      收件人地址
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param cc      抄送地址
     */
    void sendSimpleMail(String to, String subject, String content, String... cc);

    /**
     * 发送HTML邮件
     *
     * @param to      收件人地址
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param cc      抄送地址
     * @throws MessagingException 邮件发送异常
     */
    void sendHtmlMail(String to, String subject, String content, String... cc) throws MessagingException;

    /**
     * 发送带附件的邮件
     *
     * @param to       收件人地址
     * @param subject  邮件主题
     * @param content  邮件内容
     * @param filePath 附件地址
     * @param cc       抄送地址
     * @throws MessagingException 邮件发送异常
     */
    void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException;

   
}
五、MailServiceImpl实现
package com.example.mail.demo;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送文本邮件
     *
     * @param to      收件人地址
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param cc      抄送地址
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content, String... cc) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        if (cc != null) {
            message.setCc(cc);
        }
        mailSender.send(message);
    }

    /**
     * 发送HTML邮件
     *
     * @param to      收件人地址
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param cc      抄送地址
     * @throws MessagingException 邮件发送异常
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content, String... cc) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        if (cc != null) {
            helper.setCc(cc);
        }
        mailSender.send(message);
    }

    /**
     * 发送带附件的邮件
     *
     * @param to       收件人地址
     * @param subject  邮件主题
     * @param content  邮件内容
     * @param filePath 附件地址
     * @param cc       抄送地址
     * @throws MessagingException 邮件发送异常
     */
    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        if (cc != null) {
            helper.setCc(cc);
        }
        FileSystemResource file = new FileSystemResource(new File(filePath));

        String fileName = new File(filePath).getName();
        System.out.println("fileName:"+fileName);
        helper.addAttachment(fileName, file);

        mailSender.send(message);
    }


}
六、EmailController控制类
package com.example.mail.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import java.io.File;
import java.net.URL;

@Controller
public class EmailController {

    @Autowired
    private MailService mailService;

    /**
     * 测试发送简单邮件
     */
    @GetMapping("/testSendSimpleMail")
    @ResponseBody
    public String sendSimpleMail() {
        mailService.sendSimpleMail("[email protected]", "这是一封简单邮件", "这是一封普通的SpringBoot测试邮件");
        return "ok";
    }

    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 发送html邮件
     * @return
     * @throws MessagingException
     */
    @GetMapping("/sendHtmlMail")
    @ResponseBody
    public String sendHtmlMail() throws MessagingException {
        Context context = new Context();
        context.setVariable("project", "Spring Boot email");
        context.setVariable("author", "万笑佛");
        context.setVariable("url", "https://www.cnblogs.com/yclh/");
        String emailTemplate = templateEngine.process("welcome", context);
        mailService.sendHtmlMail("[email protected]", "这是一封模板HTML邮件", emailTemplate);
        return "ok";
    }


    /**
     * 发送带附件的邮件
     * @throws MessagingException
     */
    @GetMapping("/sendAttachmentsMail")
    @ResponseBody
    public String sendAttachmentsMail() throws MessagingException {
        URL url = null;
        try {
            // 创建一个文件对象
            File file = new File("D:\\IDEANew\\45Mail\\src\\main\\resources\\static\\index.html");
            // 将文件对象转换为URI
            url = file.toURI().toURL();
            // 输出URL
            System.out.println("文件的URL: " + url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(url.getPath());
        mailService.sendAttachmentsMail("[email protected]", "这是一封带附件的邮件", "邮件中有附件,请注意查收!", url.getPath());
        return "ok";
    }



}
七、postman测试
(1)第一个简单邮件

 

效果

(2)第二个带模板的邮件

效果

 

(3)第三个带附件的邮件

 

效果

 

 

 

标签:Springboot,cc,param,发送,import,mail,邮件,String
From: https://www.cnblogs.com/yclh/p/17852019.html

相关文章

  • HAL_RS485发送接收_DMA:编码器
    RS485编码器使用RS485读取多个编码器接收数据:空闲中断+DMA发送数据:DMA配置串口:基本与串口通信一致,增加接收和发送DMA,正常模式,另外增加485使能IO      接收数据:使能空闲中断        __HAL_UART_ENABLE_IT(&huart3,UART_IT_IDLE);        _......
  • spring和springboot定时任务线程池配置
    spring和springboot定时任务线程池配置目录spring和springboot定时任务线程池配置1背景2配置2.1命名空间配置2.2yaml配置3参考文档1背景项目有几个新增的月末报表生成定时任务(使用spring内置的TaskScheduler),相关业务人员反馈报表没有及时生成,让我比较疑惑:虽然生成比较耗......
  • java 实现文件夹上传(springBoot 框架)
    java实现文件夹上传(springBoot框架)有时我们后台管理等服务可能会有这样一个简单需求,就是根据文件夹将整个文件夹下的所有资源都上传到我们的服务器上,本人也是搜索了大量资料,最终以最简单便捷的方式实现该功能,具体操作步骤如下一、前端如何设置上传组件并将资源上传到后台服务这......
  • 命令行非交互式发送邮件ForWindows
    2个工具Cmail(更加推荐):https://www.inveigle.net/cmail发现的问题:如果需要调用外部txt作为邮件的body部分,那么该文本编码必须为utf-8下载:https://www.inveigle.net/cmail/download最佳配置实践:https://www.inveigle.net/cmail/examples Blat:https://www.blat.net/下载:https......
  • 使用jasypt对springboot配置信息加密
    1.pom文件增加依赖<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>3.0.5</version> </dependency>2.修改启动......
  • 手把手教你玩转 SpringBoot 日志
    本文根据文章:https://lebron.blog.csdn.net/article/details/132953586?spm=1001.2014.3001.5502进行修改一、日志重要吗程序中的日志重要吗?在回答这个问题前,笔者先说个事例:笔者印象尤深的就是去年某个同事,收到了客户反馈的紧急bug。尽管申请到了日志文件,但因为很多关键步骤......
  • 企业微信——给国外的邮箱发邮件报错Authentication results: DKIM = did not pass
    前言发件人([email protected])域名的DNS记录未设置或设置错误导致对方拒收此邮件。hostgmail-smtp-in.l.google.com[172.253.118.27]said:550-5.7.26Thismailhasbeenblockedbecausethesenderisunauthenticated.Gmailrequiresallsenderstoauthenticatewitheither......
  • 阿里云 服务器 邮件发送
    使用SMTP(简单邮件传输协议)发送邮件一般都是使用默认的25端口,而阿里云服务器为了安全将25端口封禁了,会出现在本机测试发送邮件功能正常,但是部署到服务器上却发送失败的情况。解决办法是向阿里云申请解封25端口,或者更换端口,建议使用587端口(有的说465可用但经过测试不可用) usingSy......
  • 基于java+springboot的酒店预定网站、酒店客房管理系统
    该系统是基于Java的酒店客房预订系统设计与实现。是给师弟开发的毕业设计。现将源代码开放出来,感兴趣的同学可以下载。演示地址前台地址:http://hotel.gitapp.cn后台地址:http://hotel.gitapp.cn/admin后台管理帐号:用户名:admin123密码:admin123功能介绍平台采用B/S结构,后端采用主......
  • springboot多文件上传代码实例及解析
    这篇文章主要介绍了springboot多文件上传代码实例及解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下一说明spingMVC支持文件上传,我们通过Apach的commons-fileupload包的CommonsMultipartResolver去实现了spingMVC的Mu......