springboot自带mail实现邮件发送

登录网易邮箱,打开POP3/SMTP/IMAP

设置授权码(发送手机短信会受到一个授权码)

引入pom.xml

        <!--邮件发送依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

application.properties

spring.mail.host=smtp.163.com
spring.mail.username=xx@163.com
spring.mail.password=xxxx
spring.mail.protocol=smtp
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.port=994
spring.mail.properties.mail.display.sendmail=xx@163.com
spring.mail.properties.mail.display.sendname=xxx
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.default-encoding=utf-8
spring.mail.from=xxxx@163.com

spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates

server.port=9999

 邮件实现

邮件实体类

package com.grm.entity;

import java.util.Map;

/**
 * 邮件
 *
 * @author gaorimao
 * @date 2022/02/17
 */
public class Mail {
    /**
     * 标题
     */
    private String title;
    /**
     * 内容
     */
    private String content;
    /**
     * 接收人邮件地址
     */
    private String to;
    /**
     * 附加,value 文件的绝对地址/动态模板数据
     */
    private Map<String, Object> attachment;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public Map<String, Object> getAttachment() {
        return attachment;
    }

    public void setAttachment(Map<String, Object> attachment) {
        this.attachment = attachment;
    }
}

service接口定义

package com.grm.service;

import com.grm.entity.Mail;

/**
 * 邮件服务
 *
 * @author gaorimao
 * @date 2022/02/17
 */
public interface MailService {
    /**
     * 发送邮件(纯文本)
     *
     * @param mail 邮件
     */
    void sendTextMail(Mail mail);

    /**
     * 发送html邮件(可带附件)
     *
     * @param mail       邮件
     * @param isShowHtml 是否显示html
     */
    void sendHtmlMail(Mail mail,boolean isShowHtml);

    /**
     * 邮件发送模板
     *
     * @param mail 邮件
     */
    void sendTemplateMail(Mail mail);
}

service实现层

package com.grm.service;

import com.grm.BusinessException;
import com.grm.entity.Mail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

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

@Slf4j
@Service
public class MailServiceImpl implements MailService {

    //template模板引擎
    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private JavaMailSender javaMailSender;

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

    @Override
    public void sendTextMail(Mail mail) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(mail.getTo());
        message.setSubject(mail.getTitle());
        message.setText(mail.getContent());
        try {
            javaMailSender.send(message);
        } catch (MailException e) {
            log.error("纯文本邮件发送失败->message:{}", e.getMessage());
            throw new BusinessException(500, "纯文本邮件发送失败");
        }
    }

    @Override
    public void sendHtmlMail(Mail mail, boolean isShowHtml) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //是否发送的邮件是富文本(附件,图片,html等)
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
            messageHelper.setFrom(from);
            messageHelper.setTo(mail.getTo());
            messageHelper.setSubject(mail.getTitle());
            //false,显示原始html代码,无效果
            messageHelper.setText(mail.getContent(),isShowHtml);
            //判断是否有附加图片等
            if(mail.getAttachment() != null && mail.getAttachment().size() > 0){
                mail.getAttachment().entrySet().stream().forEach(entrySet -> {
                    try {
                        File file = new File(String.valueOf(entrySet.getValue()));
                        if(file.exists()){
                            messageHelper.addAttachment(entrySet.getKey(), new FileSystemResource(file));
                        }
                    } catch (MessagingException e) {
                        log.error("附件发送失败->message:{}",e.getMessage());
                        throw new BusinessException(500,"附件发送失败");
                    }
                });
            }
            //发送
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("富文本邮件发送失败->message:{}",e.getMessage());
            throw new BusinessException(500,"富文本邮件发送失败");
        }
    }

    @Override
    public void sendTemplateMail(Mail mail) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
            messageHelper.setFrom(from);
            messageHelper.setTo(mail.getTo());
            messageHelper.setSubject(mail.getTitle());
            //使用模板thymeleaf
            Context context = new Context();
            //定义模板数据
            context.setVariables(mail.getAttachment());
            //获取thymeleaf的html模板
            String emailContent = templateEngine.process("mail1.html",context); //指定模板路径
            messageHelper.setText(emailContent,true);
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("模板邮件发送失败->message:{}",e.getMessage());
            throw new BusinessException(500,"模板邮件发送失败");
        }
    }
}

controller层

package com.grm.controller;

import com.grm.entity.Mail;
import com.grm.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/mail")
public class MailController {
    @Autowired
    private MailService mailService;

    @PostMapping("/str")
    public String strMail(@RequestBody Mail mail){
        try {
            mailService.sendTextMail(mail);
        } catch (Exception e) {
            return "failed";
        }
        return "success";
    }

    @PostMapping("/html")
    public String htmlMail(@RequestBody Mail mail){
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("收入证明模板.pdf","D:\\收入证明模板.pdf");
            mail.setAttachment(map);
            mailService.sendHtmlMail(mail,true);
        } catch (Exception e) {
            return "failed";
        }
        return "success";
    }


    @PostMapping("/template")
    public String templateMail(@RequestBody Mail mail){
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("username","grm");
            mail.setAttachment(map);
            mailService.sendTemplateMail(mail);
        } catch (Exception e) {
            return "failed";
        }
        return "success";
    }
}

 测试

测试string

 测试html,带附件

 

测试thymleaf模板

 

至此,邮件功能基本完成 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,你需要在 Spring Boot 项目中添加 Redis 和 Spring Mail 的依赖。 ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 然后,你需要在 application.properties 文件中配置 Redis 和 Mail 相关的属性。 ``` # Redis spring.redis.host=127.0.0.1 spring.redis.port=6379 # Mail spring.mail.host=smtp.gmail.com spring.mail.port=587 spring.mail.username=your-email@gmail.com spring.mail.password=your-email-password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true ``` 接着,你需要创建一个 Redis 队列,用于存储待发送邮件的信息。可以使用 RedisTemplate 来操作 Redis 队列。 ``` @Autowired private RedisTemplate<String, Object> redisTemplate; public void sendEmail(String to, String subject, String content) { Email email = new Email(to, subject, content); redisTemplate.opsForList().leftPush("email_queue", email); } ``` 最后,你需要创建一个定时任务,从 Redis 队列中取出邮件信息,并使用 JavaMailSender 发送邮件。 ``` @Autowired private JavaMailSender javaMailSender; @Scheduled(fixedDelay = 1000) public void sendEmailFromQueue() { Email email = (Email) redisTemplate.opsForList().rightPop("email_queue"); if (email != null) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(email.getTo()); message.setSubject(email.getSubject()); message.setText(email.getContent()); javaMailSender.send(message); } } public class Email { private String to; private String subject; private String content; public Email(String to, String subject, String content) { this.to = to; this.subject = subject; this.content = content; } // getters and setters } ``` 这样,你就可以使用 Redis 自动发送邮件了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值