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

spring boot发送邮件

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

spring boot发送邮件

学习记录 

1、安装项目依赖

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


2、配置application.properties

spring.mail.host=smtp.qq.com
spring.mail.username=发送方qq@qq.com
spring.mail.password=授权码
spring.mail.properties.mail.smtp.port=465
spring.mail.from=发送方qq@qq.com

3、SendEmailServer .java 发送邮件的业务层

package com.example.iot_kcsj.server;

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;

import javax.annotation.Resource;


@Service
public class SendEmailServer {

//    这里需要注意,一开始我用的是@Autowired注解,但是不能注入JavaMailSender,具体原因我也不太清楚
    @Resource
    JavaMailSender javaMailSender;

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

    public void sendSimpleMail(String to, String subject, String content) {
        //创建SimpleMailMessage对象
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件发送人
        message.setFrom("2038834512@qq.com");
        //邮件接收人
        message.setTo(to);
        //邮件主题
        message.setSubject(subject);
        //邮件内容
        message.setText(content);
        //发送邮件
        javaMailSender.send(message);
    }
}

4、SendEmailController.java 发送邮件控制层

package com.example.iot_kcsj.controller;

import com.example.iot_kcsj.server.SendEmailServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class SendEmailController {

    @Autowired
    SendEmailServer mailService;

    @GetMapping("/send_email")
    public void sendEmail(){
        mailService.sendSimpleMail("发送方qq@qq.com","主题:你好普通邮件","内容:第一封邮件");
    }
}

5、目录结构

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/926970.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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