java实现发送邮件

本文介绍了如何在SpringBoot项目中配置Mail依赖,包括添加QQ邮箱服务器信息,获取授权码,以及使用JavaMailSender发送简单邮件、HTML格式邮件、带附件的邮件和带静态资源的邮件。同时,展示了如何设置定时任务使用cron表达式进行周期性邮件发送。
摘要由CSDN通过智能技术生成

导入Mail依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>jakarta.mail</artifactId>
            <version>1.6.7</version>
            <scope>compile</scope>
        </dependency>

邮箱链接配置

spring:
  mail:
    protocol: smtps
    host: smtp.163.com  #qq邮件服务器地址 有其他地址
    username: dfh_414@163.com #发件人邮箱
    password: KSFIDNNNLZCVLAUT #授权码
    default-encoding: UTF-8 #邮件登录字符集编码
    port: 465 #发件人邮件服务器端口

    properties:
      mail:
        stmp:
          ssl:
            enable: true

如何获取授权码(qq邮箱示范)

1.首先登录qq,打开邮箱的设置。
在这里插入图片描述
2.找到设置里面的账户。
在这里插入图片描述
3.然后可以看到生成授权码,我们点击,然后按要求发送短信即可。
在这里插入图片描述

发送邮件的逻辑

简单邮件、HTML格式邮件、带附件的邮件、带静态资源的邮件。

package com.dfh.time.util;

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.Component;

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

/**
 * @author dfh
 * @date 2022/9/28 10:15
 */

@Component
public class MailUtil {
    @Value("${spring.mail.username}")
    String from;

    @Autowired
    JavaMailSender mailSender;
    
    //简单邮件
    public void sendSimpleMail(String to, String subject, String content){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from); //发件人
        message.setTo(to);//收件人
        message.setSubject(subject); //标题
        message.setText(content);   //文件内容

        try {
            mailSender.send(message);
            System.out.println("简单邮件发送成功!");
        } catch (Exception e){
            System.out.println("发送简单邮件时发生异常!"+e);
        }
    }
    
    
    //html格式邮件
    public void sendHtmlMail(String to, String subject, String content){
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            mailSender.send(message);
            System.out.println("html邮件发送成功!");
        } catch (MessagingException e) {
            System.out.println("发送html邮件时发生异常!"+e);
        }
    }

    
    //带附件的邮件
    public void sendAttachmentsMail(String to, String subject, String content, String filePath){
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);

            mailSender.send(message);
            System.out.println("带附件的邮件已经发送。");
        } catch (MessagingException e) {
            System.out.println("发送带附件的邮件时发生异常!" + e);
        }
    }

    //带静态资源的邮件
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);

            mailSender.send(message);
            System.out.println("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException e) {
            System.out.println("发送嵌入静态资源的邮件时发生异常!" + e);
        }
    }
}

测试类

编写邮件内容,运行代码,发送邮件。

package com.dfh.time;

import com.dfh.time.util.MailUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

@SpringBootTest
class TimeApplicationTests {


    @Autowired
    MailUtil mailUtil;

    //发送简单邮件测试
    @Test
    void contextLoads() {
        mailUtil.sendSimpleMail("1724054751@qq.com","标题","内容");

    }
    //发送HTML邮件
    @Test
    void testHtmlMail() {
        String content="<html>\n" +
                "<body>\n" +
                "    <h3>hello world ! 这是一封Html邮件!</h3>\n" +
                "</body>\n" +
                "</html>";
        mailUtil.sendHtmlMail("1724054751@qq.com","test simple mail",content);
    }
    //发送带附件的邮件
    @Test
    void sendAttachmentsMail() {
        String filePath="C:\\Happy\\pictures\\word.doc";
        mailUtil.sendAttachmentsMail("1724054751@qq.com", "主题:带附件的邮件", "有附件,请查收!", filePath);
    }

    //发送带静态资源(图片)
    @Test
    void sendInlineResourceMail() {
        String rscId = "neo006";
        String content="<html><body>这是有图片的邮件:<img src=\'cid:" + rscId + "\' ></body></html>";
        String imgPath = "C:\\Happy\\pictures\\锤石.png";
        mailUtil.sendInlineResourceMail("1724054751@qq.com", "主题:这是有图片的邮件", content, imgPath, rscId);
        //添加多个图片可以使用多条 <img src='cid:" + rscId + "' > 和 helper.addInline(rscId, res) 来实现
    }

}

定时任务发送邮件

    //定时发送邮件
    @Autowired
    private MailUtil mailUtil;
    @Async
    @Scheduled(cron = "0 0 12 ? * WED")
    public void task() {
        mailUtil.sendSimpleMail("1724054751@qq.com", "2022年9月28日-duanfh-写代码", "定时发送邮件");
    }

定时任务的时间设置

*/5 * * * * ?  每五秒一次
* */5 * * * ?  每五分一次
0 0 10,14,16 * * ?  每天上午10点,下午2点,40 0/30 9-17 * * ?  朝九晚五工作时间内每半小时
0 0 12 ? * WED  表示每个星期三中午120 0 12 * * ?  每天中午12点触发
0 15 10 ? * *  每天上午10:15触发
0 15 10 * * ?  每天上午10:15触发
0 15 10 * * ? *  每天上午10:15触发
0 15 10 * * ? 2005  2005年的每天上午10:15触发
0 * 14 * * ?  在每天下午2点到下午2:59期间的每1分钟触发
0 0/5 14 * * ?  在每天下午2点到下午2:55期间的每5分钟触发
0 0/5 14,18 * * ?  在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
0 0-5 14 * * ?  在每天下午2点到下午2:05期间的每1分钟触发
0 10,44 14 ? 3 WED  每年三月的星期三的下午2:102:44触发
0 15 10 ? * MON-FRI 周一至周五的上午10:15触发
0 15 10 15 * ? 每月15日上午10:15触发
0 15 10 L * ? 每月最后一日的上午10:15触发
0 15 10 ? * 6L 每月的最后一个星期五上午10:15触发
0 15 10 ? * 6L 2002-2005  2002年至2005年的每月的最后一个星期五上午10:15触发
0 15 10 ? * 6#3 每月的第三个星期五上午10:15触发
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值