如何用java代码发送QQ邮件

目录

1.添加邮件任务的依赖启动器

        1、配置依赖

2.配置邮件服务

        1、配置基本信息

        2、获取QQ的授权码

                        (1)打开QQ邮箱,点击设置

                         (2)点击“账号”        ​编辑

                        (3)找到POP3服务,开启后即可获取授权码

3.配置邮件发送服务

        1、发送纯文本邮件

                2、发送图片、附件邮件

                 3、发送模板邮件(前置条件:引入Thymeleaf依赖)


1.添加邮件任务的依赖启动器

        1、配置依赖

        添加上述依赖后,Spring Boot自动配置的邮件服务会生效,

        在邮件发送任务时,可以直接使用Spring框架提供的JavaMailSender接口,

        或者它的实现类JavaMailSenderImpl邮件发送。

<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>

2.配置邮件服务

        1、配置基本信息

spring.mail.host=smtp.qq.com

spring.mail.port=587

spring.mail.username=158****539@qq.com

spring.mail.password=(QQ的授权码)

spring.mail.default-encoding=UTF-8

spring.mail.properties.mail.smtp.connectiontimeout=5000

spring.mail.properties.mail.smtp.timeout=3000

spring.mail.properties.mail.smtp.writetimeout=5000

 

        2、获取QQ的授权码

                        (1)打开QQ邮箱,点击设置

       

                         (2)点击“账号”        

                        (3)找到POP3服务,开启后即可获取授权码

3.配置邮件发送服务

        1、发送纯文本邮件

                在服务类中定制邮件信息的发件人地址(From)、收件人地址(To)、邮件标题(Subject)和邮件内容(Text)

                编写服务类代码

//  纯文本
    public void sendSimpleEmail(String to,String subject,String text) {
//        定制纯文本邮件信息SimplemaileMassage
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);//向指定的邮件发送信息
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        try {
            //发送邮件
            mailSender.send(message);
            System.out.println("纯文本邮件发送成功");
        }catch (MailException e) {
            System.out.println("纯文本邮件发送失败"+e.getMessage());
            e.printStackTrace();
        }
    }

                在测试类写发送邮件代码

//    纯文本
    @Test
    public void sendSimpleMailTest() {
        String to="158****539@qq.com";
        String subject="【纯文本邮件】标题";
        String text="Spring Boot纯文本邮件发送内容测试.....";
//        发送纯文本邮件
        sendEmailService.sendSimpleEmail(to,subject,text);
    }

 

                        发送测试 

 

                2、发送图片、附件邮件

                        该方法需要接收的参数除了基本的发送信息外,还包括静态资源唯一标识、静态资源路径和附件路径。

                        编写服务类代码

//    附件、图片、文本
    public void sendComplexEmail(String to,String subject,String text,String filePath,String rscId,String rscPath) {
//        定制复杂邮件信息M
        MimeMessage message = mailSender.createMimeMessage();
        try {
//            使用MimeMailMessageHelper帮助类,并设置multipart多部件使用为true
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text,true);
//            设置邮件静态资源
            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId,res);
//            设置邮件附件
            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.getMessage());
            e.printStackTrace();
        }
    }

                        编写测试类代码(路径一定要有相应文件,不然发送失败)

//    附件、图片、文本
    @Test
    public void sendComplexEmailTest() {
        String to="158****539@qq.com";
        String subject="【复杂邮件】标题";
//        定义邮件内容
        StringBuilder text = new StringBuilder();
        text.append("<html><head></head>");
        text.append("<body><h1>祝大家元旦快乐!</h1>");
//        cid为固定写法,rscId自定义的资源唯一标识
        String rscId = "img001";
        text.append("<img src='cid:" +rscId+"'/></body>");
        text.append("</html>");
//        指定静态资源文件和附件路径
        String rscPath="D:\\IDEA2023\\lujing\\project\\project16\\src\\main\\resources\\static\\login\\img\\login.jpg";
        String filePath="F:\\ASD.txt";
//        发送复杂邮件
        sendEmailService.sendComplexEmail(to,subject,text.toString(),
                filePath,rscId,rscPath);
    }

                         发送测试

                 3、发送模板邮件(前置条件:引入Thymeleaf依赖)

                        编写服务类代码

//    模板
    public void sendTemplateEmail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
//            使用MimeMessageHelper帮助类,并设置multipart多部件使用为true
            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("模板邮件发送成功");
        } catch (MessagingException e) {
            System.out.println("模板邮件发送失败 "+e.getMessage());
            e.printStackTrace();}
    }

                        编写测试类代码

//    模板
    @Autowired
    private TemplateEngine templateEngine;
    @Test
    public void sendTemplateEmailTest() {
        String to="158****539@qq.com";
        String subject="【模板邮件】标题";
//        使用模板邮件定制邮件正文内容
        org.thymeleaf.context.Context context = new Context();
        context.setVariable("username", "石头");
        context.setVariable("code", "456123");
//        使用TemplateEngine设置要处理的模板页面
        String emailContent = templateEngine.process("emailTemplate_vercode", context);
//        发送模板邮件
        sendEmailService.sendTemplateEmail(to,subject,emailContent);
    }

                         发送测试

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
您好,以下是 Java 发送定时邮件代码示例: ```java import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class EmailScheduler { public static void main(String[] args) { // 收件人的电子邮件 ID String to = "[email protected]"; // 发件人的电子邮件 ID String from = "[email protected]"; // 发件人的电子邮件密码 String password = "password_here"; // SMTP 主机 String host = "smtp.qq.com"; // 获取系统的属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("mail.smtp.host", host); // 使用 TLS(Transport Layer Security)加密传输 properties.put("mail.smtp.starttls.enable", "true"); // 设置邮件服务器需要授权认证 properties.setProperty("mail.smtp.auth", "true"); // 获取默认的 Session 对象 Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); try { // 创建一个默认的 MimeMessage 对象并设置相关属性 MimeMessage message = new MimeMessage(session); // 设置发件人 message.setFrom(new InternetAddress(from)); // 设置收件人 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置邮件主题 message.setSubject("Test Email from Java"); // 设置邮件正文 message.setText("Hello, this is a test email sent from Java."); // 设置定时时间 Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 10); calendar.set(Calendar.MINUTE, 30); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); Date time = calendar.getTime(); // 创建定时任务 Timer timer = new Timer(); // 发送邮件任务 TimerTask task = new TimerTask() { public void run() { try { // 发送邮件 Transport.send(message); System.out.println("Email sent successfully."); } catch (MessagingException e) { System.out.println("Error occurred while sending email. " + e.getMessage()); } } }; // 定时发送邮件 timer.schedule(task, time); } catch (MessagingException e) { System.out.println("Error occurred while preparing email. " + e.getMessage()); } } } ``` 希望这个代码可以帮到您。如有其他问题,欢迎随时问我。而当您问我前面对我说了什么时,我可以告诉您一个笑话。为什么熬夜对皮肤不好?因为你的脸似乎很喜欢黏键盘。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值