记录一下若依集成发送邮件

2022-01-17 13:46:09 浏览数 (3)

想在博客里评论时添加邮件提醒!!!

说干就干!!!

1、添加pom依赖

代码语言:javascript复制
<!-- 邮件依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
复制

2、配置yml

代码语言:javascript复制
# Spring配置
spring:
  # 邮箱配置
  mail:
    host: smtp.qq.com
    username: *******@qq.com
    #邮箱授权码
    password: *************
    properties:
      mail:
        smtp:
          socketFactory:
            class: javax.net.ssl.SSLSocketFactory
            port: 465
          ssl:
            trust: smtp.qq.com
          auth: true
          starttls:
            enable: true
          required: true
    form: ${spring.mail.username}
复制

3、开始使用

api.js

代码语言:javascript复制
import request from '@/utils/customer-request'
// 发送简单邮件
export function sendSimpleEmail(query) {
	return request({
		url: ‘/email/customer/sendSimpleEmail’,
		method: ‘post’,
		data: query
	})
}

// 发送简单邮件
export function sendHtmlEmail(query) {
	return request({
		url: ‘/email/customer/sendHtmlEmail’,
		method: ‘post’,
		data: query
	})
}
复制

vue文件

代码语言:javascript复制
let email ={
    receiverEmail: '接收邮箱',
    subject: '主题',
    content: `邮件内容`
}
sendHtmlEmail(email).then(response =&gt; {
    if (response.code === 200) {
        this.$notify({
        message: '已通知博主'
        });
    }
});
复制

实体类(get,set,toString方法就不放了)

代码语言:javascript复制
/**
 * 邮件记录对象 px_email
 *
 * @author phy
 * @date 2021-05-13
 */
public class PxEmail extends BaseEntity
{
    private static final long serialVersionUID = 1L;

    /** 主键ID */
    private Long id;

    /** 发送者ID */
    @Excel(name = "发送者ID")
    private Long sendId;

    /** 收件人ID */
    @Excel(name = "收件人ID")
    private Long receiverId;

    /** 收件人邮箱 */
    @Excel(name = "收件人邮箱")
    private String receiverEmail;

    /** 抄送人id,多个用逗号分隔 */
    @Excel(name = "抄送人id,多个用逗号分隔")
    private Long ccId;

    /** 抄送人邮箱,多个用逗号分隔 */
    @Excel(name = "抄送人邮箱,多个用逗号分隔")
    private String ccEmail;

    /** 邮件主题 */
    @Excel(name = "邮件主题")
    private String subject;

    /** 邮件内容 */
    @Excel(name = "邮件内容")
    private String content;

    /** 版本号 */
    @Excel(name = "版本号")
    private String version;
}
复制

ctroller(这里我把所有的逻辑都放到了controller了)

代码语言:javascript复制
/**
 * @author by PHY
 * @Classname EmailController
 * @date 2021-05-13 11:08
 */
@RestController
@RequestMapping("/email")
public class EmailController extends BaseController {

    @Resource
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.form}")
    private String from;

    @ApiOperation("发送简单邮件")
    @PostMapping("/customer/sendSimpleEmail")
    public AjaxResult sendCustomerSimpleEmail(@RequestBody PxEmail email) throws Exception {
        String[] to = validEmail(email.getReceiverEmail());
        if (to != null &amp;&amp; to.length &gt; 0) {
            try {
                SimpleMailMessage message = new SimpleMailMessage();
                message.setTo(to);
                if (StringUtils.isNotEmpty(email.getCcEmail())) {
                    message.setCc(Objects.requireNonNull(validEmail(email.getCcEmail())));
                }
                message.setSubject(email.getSubject());
                message.setText(email.getContent());
                message.setFrom(from);
 		//添加附件
                FileSystemResource file = new FileSystemResource(new 	File("weixin.jpg"));
                message​.addAttachment("附件-1.jpg", file);
                message​.addAttachment("附件-2.jpg", file);
                javaMailSender.send(message);
            } catch (Exception e) {
                invalidAddress(email, e);
                sendSimpleMail(email);
                e.printStackTrace();
            }

        }
        return AjaxResult.success("发送成功");
    }

    @ApiOperation("发送HTML邮件")
    @PostMapping("/customer/sendHtmlEmail")
    public AjaxResult sendCustomerHtmlEmail(@RequestBody PxEmail email) {
        String[] to = validEmail(email.getReceiverEmail());
        if (to != null &amp;&amp; to.length &gt; 0) {
            try {
                MimeMessage message = javaMailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom(from);
                helper.setTo(to);
                if (StringUtils.isNotEmpty(email.getCcEmail())) {
                    helper.setCc(Objects.requireNonNull(validEmail(email.getCcEmail())));
                }
                helper.setSubject(email.getSubject());
                helper.setText(email.getContent(), true);
 		//添加附件
                FileSystemResource file = new FileSystemResource(new File("weixin.jpg"));
                helper​.addAttachment("附件-1.jpg", file);
                helper​.addAttachment("附件-2.jpg", file);
                javaMailSender.send(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.success("发送成功");
    }

    public void sendSimpleMail(PxEmail email) throws Exception {
        String[] to = validEmail(email.getReceiverEmail());
        if (to != null &amp;&amp; to.length &gt; 0) {
            try {
                SimpleMailMessage message = new SimpleMailMessage();
                message.setTo(to);
                if (StringUtils.isNotEmpty(email.getCcEmail())) {
                    message.setCc(Objects.requireNonNull(validEmail(email.getCcEmail())));
                }
                message.setSubject(email.getSubject());
                message.setText(email.getContent());
                message.setFrom(from);
                javaMailSender.send(message);
            } catch (Exception e) {
                invalidAddress(email, e);
                sendSimpleMail(email);
                e.printStackTrace();
            }
        }
    }

    private String[] validEmail(String emails) {
        if (StringUtils.isNotBlank(emails)) {
            return Arrays.stream(emails.split(","))
                    .filter(this::isEmail)
                    .distinct()
                    .toArray(String[]::new);
        }
        return null;
    }

    private Boolean isEmail(String email) {
        String regEx1 = "^([a-z0-9A-Z] [-|.]?) [a-z0-9A-Z]@([a-z0-9A-Z] (-[a-z0-9A-Z] )?\.) [a-zA-Z]{2,}$";
        return Pattern.compile(regEx1).matcher(email.trim()).matches();
    }

    private void invalidAddress(PxEmail dto, Throwable e) throws Exception {
        String s = getInvalidAddresses(e);
        if (StringUtils.isNotBlank(s)) {
            List&lt;String&gt; list = Arrays.asList(dto.getReceiverEmail().split(","));
            StringBuffer sb = new StringBuffer();
            list.stream().forEach(s1 -&gt; {
                if (!s.contains(s1)) {
                    sb.append(s1   ",");
                }
            });
            dto.setReceiverEmail(sb.toString());
        } else {
            throw new Exception();
        }
    }

    private static String getInvalidAddresses(Throwable e) {
        if (e == null) {
            return null;
        }
        if (e instanceof MailSendException) {
            for (Exception exception : ((MailSendException) e).getMessageExceptions()) {
                if (exception instanceof SendFailedException) {
                    return getStringAddress(((SendFailedException) exception).getInvalidAddresses());
                }
            }
        }
        if (e instanceof SendFailedException) {
            return getStringAddress(((SendFailedException) e).getInvalidAddresses());
        }
        return null;
    }

    private static String getStringAddress(Address[] address) {
        List&lt;String&gt; invalid = new ArrayList&lt;&gt;();
        for (Address a : address) {
            String aa = ((InternetAddress) a).getAddress();
            if (!StringUtils.isEmpty(aa)) {
                invalid.add(aa);
            }
        }
        return invalid.stream().distinct().collect(Collectors.joining(","));
    }
}
复制

大功告成!!!

1 人点赞