Live2D

基于JavaEmail 和xxl-job的定时邮件发送

1.JavaEmail接口-SpringBoot

Maven依赖

<dependency>
      <groupId>com.sun.mail</groupId>
      <artifactId>javax.mail</artifactId>
      <version>1.6.2</version>
</dependency>

接口代码

package com.yebenandwangliang.utils.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

@Controller
@RequestMapping("email")
public class EmailController {

    @PostMapping("/sendEmail")
    @ResponseBody
    public String sendEmail() throws Exception {
        // 获取配置文件的内容
        Properties emailProperties = new Properties();
        emailProperties.load(EmailController.class.getClassLoader().getResourceAsStream("email.properties"));
        // 设置参数
        Properties props = new Properties();
        // 基于smtp
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", emailProperties.getProperty("SMTPEmailHost"));
        props.setProperty("mail.smtp.auth", "true");

        // 创建会话
        Session session = Session.getInstance(props);
        session.setDebug(true);
        // 创建邮件
        MimeMessage message = createMessage(session, emailProperties.getProperty("sendEmail"), emailProperties.getProperty("receiveEmail"));
        // 获取传输对象
        Transport transport = session.getTransport();
        transport.connect(emailProperties.getProperty("emailAccount"),emailProperties.getProperty("emailPassword"));
        // 发送邮件
        // message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
        transport.sendMessage(message,message.getAllRecipients());
        // 关闭连接
        transport.close();
        return "send finish";

    }

    private static MimeMessage createMessage(Session session, String sendEmail, String receiveEmail) throws Exception {
        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);

        // 发件人
        message.setFrom(new InternetAddress(sendEmail, "QQ邮箱助手", "UTF-8"));
        // 收件人
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveEmail, "User", "UTF-8"));

        // 邮件主题
        message.setSubject("穿越火线权益", "UTF-8");
        // 邮件正文
        message.setContent("恭喜你成为穿越火线本周幸运星,你将获得一折的特殊权益", "text/html;charset=UTF-8");
        // 邮件的发送日期
        message.setSentDate(new Date());
        // 保存前面的设置
        message.saveChanges();
        return message;
    }
}

email.properties

# 发件人邮箱
sendEmail=12@qq.com
# 收件人邮箱
receiveEmail=2222@qq.com
# smtp服务器地址
SMTPEmailHost=smtp.qq.com
# 自己的邮箱和授权码
emailAccount=
emailPassword=

2.xxl-job配置

ui界面配置如下:
image

posted @ 2022-03-21 17:06  没有梦想的java菜鸟  阅读(621)  评论(0编辑  收藏  举报