zl程序教程

您现在的位置是:首页 >  后端

当前栏目

使用Java代码给邮箱发送电子邮件

JAVA代码 发送 邮箱 电子邮件 使用
2023-09-11 14:22:31 时间

前言

使用Java代码发送邮箱,这里以qq邮箱为例

1.开启qq邮箱开启IMAP/SMTP服务*

首先进入qq邮箱

在这里插入图片描述

点击设置

在这里插入图片描述

点击账户,然后往下拉

在这里插入图片描述

开启IMAP/SMTP服务

在这里插入图片描述

开启成功得到授权密码,这个要记住,一会用

2.引入pom依赖

  <!--发送邮箱-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>

3.配置application.properties

# QQ邮箱配置
spring.mail.host=smtp.qq.com
#发件人QQ邮箱地址
spring.mail.username=xxxx
#QQ邮箱授权码 得到的授权密码
spring.mail.password=xxxx 
#以下三项不用改动
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

4.编写接口

这里的收件邮箱,记得换成参数哦

package com.wyh.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.mail.Address;
import javax.mail.MessagingException;
import java.util.ArrayList;

@RestController
public class EmailController {
    @Resource
    private JavaMailSender javaMailSender;
    //这一步是获取application.properties中设置的发件人邮箱地址
    @Value("${spring.mail.username}")
    private String username;
   /**
    * @Description  发送邮箱
    * @Date 0:09 2021/5/19
    * @return void
   **/
    @RequestMapping("/sendEmail")
    public String  sendMail(String eamil) {
            SimpleMailMessage message = new SimpleMailMessage();
            //发件人邮件地址(上面获取到的,也可以直接填写,string类型)
            message.setFrom(username);
            //要发送的qq邮箱(收件人地址)
            message.setTo(eamil);
            //邮件主题
            message.setSubject("java调用QQ邮箱发送");
            //邮件正文
            message.setText("我是用java发送的QQ邮箱");
            javaMailSender.send(message);
            return "发送成功!";
    }
}

5.查看效果

可以用接口工具去测试

在这里插入图片描述

在这里插入图片描述