SpringBoot使用JavaMailSender实现发送邮件功能

1.在pom.xml中导入 spring-boot-starter-mail 依赖


<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-mailartifactId>
    <version>2.1.1.RELEASEversion>
dependency>

2.配置application.properties

# spring-mail
spring.mail.host=smtp.qq.com
spring.mail.username=2386615000@qq.com

# 先要去邮箱获取属于自己邮箱的授权码(注意 : 此授权码我已修改...无效了)
spring.mail.password=sxwrwevodyldigb

spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

# 端口号,不设置默认为25,而端口号25现已被很多云服务商禁用,如果非要用25,需申请解封,这里使用端口号:465
spring.mail.port=465
spring.mail.properties.mail.smtp.socketFactory.port = 465
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback = false

3.开放465端口号 , 注意:我使用的是centos7.3的版本,防火墙是firewall

firewall-cmd --zone=public --add-port=465/tcp --permanent

3.重启防火墙,运行命令:

firewall-cmd --reload

4.查看端口号是否开启,运行命令:

firewall-cmd --query-port=465/tcp

5.如果是阿里云的服务器 , 还需进入服务器管理控制台,给防火墙465端口号添加规则

SpringBoot使用JavaMailSender实现发送邮件功能_第1张图片

6.定义邮件发送工具类

package com.bhy702.website.common.validateUtil;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

/**
 * @author: Hongyuan Bai
 * @create: 2018-12-15 10:49:48
 * @description:
 */
public class SendToMail{

    public static void sendSimpleMail(JavaMailSender javaMailSender, String email,String username, String message){

        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        //邮件发送方
        simpleMailMessage.setFrom("bhy702"+"<"+"[email protected]"+">");
        //邮件接收方邮箱
        simpleMailMessage.setTo(email);
        //邮件标题
        simpleMailMessage.setSubject("【个人网站通知】:老大,有新增留言信息通知~~");
        //邮件内容
        simpleMailMessage.setText(username+" : "+message);
		//发送邮件
        javaMailSender.send(simpleMailMessage);
    }
}

7. service层 调用邮件发送工具类 : SendToMail.sendSimpleMail() 方法发送邮件

package com.bhy702.website.service;

import com.bhy702.website.common.validateUtil.SendToMail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * @author: Hongyuan Bai
 * @create: 2019-01-16 15:12:09
 * @description:
 */
@Service
public class SendMessageService {

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * @Description: 邮箱留言邮件
     * @Param: [email, username, message]
     * @return: boolean
     */
    public boolean sendMessageForMe(String email, String username, String message) {
        //发送留言邮件
        SendToMail.sendSimpleMail(javaMailSender,email,username,message);
        return true;
    }
}

欢迎访问本文的个人博客链接: https://br-bai.github.io/2019/01/17/SpringBoot使用JavaMailSender实现发送邮件功能/

你可能感兴趣的:(功能开发)