springboot 发送邮件

package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MailController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${mail.fromMail.sender}")
    private String sender;

    @Value("${mail.fromMail.receiver}")
    private String receiver;

    @Autowired
    private JavaMailSender javaMailSender;

    @RequestMapping("/sendMail")
    public String sendMail() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sender);
        message.setTo(receiver);
        message.setSubject("测试邮件!!!!!");
        message.setText("hello!");
        try {
            javaMailSender.send(message);
            logger.info("邮件已经发送。");
        } catch (Exception e) {
            logger.error("发送异常!", e);
        }
        return "success";
    }
}

配置文件信息:

server.port= 9000

##这里根据自己的情况填写
##邮箱服务器地址
##QQ smtp.qq.com
##sina smtp.sina.cn
##aliyun smtp.aliyun.com
##163 smtp.163.com
spring.mail.host=smtp.qq.com
##邮箱用户名
spring.mail.username=xxx
##邮箱密码(注意:qq邮箱去设置,账户中获得,不明白看链接:https://jingyan.baidu.com/article/90895e0f2af42664ec6b0b14.html)
spring.mail.password=xxx
##编码格式
spring.mail.default-encoding=UTF-8

##发送邮件地址
mail.fromMail.sender=发送邮箱
##接收邮件地址
mail.fromMail.receiver=接受邮箱

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章