栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot 发送邮件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot 发送邮件

这里以QQ邮箱为例:
1.打开QQ邮箱,点击“设置”

2.打开“账户”

3.打开服务,并生成授权码

注意授权码记下来!!!

springboot引入依赖

        
            org.springframework.boot
            spring-boot-starter-mail
        

编写配置文件yml

spring:
  mail:
    host: smtp.qq.com
    username: your email accout
    password: auth code
    default-encoding: utf-8
    protocol: smtp
    port: 587

接下来定义接口

import cn.hutool.extra.mail.MailException;

public interface MailService {
    
    void sendSimpleMail(String to, String subject, String content) throws MailException;
}

}

实现接口

import cn.hutool.extra.mail.MailException;
import com.ihep.astro.service.MailService;
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.stereotype.Service;


@Service
public class MailServiceImpl implements MailService {
    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendSimpleMail(String to, String subject, String content) throws MailException {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from); // 邮件发送者
        message.setTo(to); // 邮件接受者
        message.setSubject(subject); // 主题
        message.setText(content); // 内容
        mailSender.send(message);
    }
}

编写测试类

import com.service.MailService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;


@RunWith(SpringRunner.class)
@SpringBootTest
public class ServiceTest {
    @Autowired
    private MailService mailService;

    @Test
    public void sendSimpleMail() {
        mailService.sendSimpleMail("123333@qq.com", "发送邮件测试", "大家好,这是我用springboot进行发送邮件测试");
    }
}

提醒自己注意:
编写配置文件yml的时候,没有写协议和端口两行,不能成功发送邮件。

spring:
  mail:
    host: smtp.qq.com
    username: wh19976552@qq.com
    password: ubvywpnzaqpbebgf
    default-encoding: utf-8
    protocol: smtp
    port: 587
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/602382.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号