邮件发送介绍和项目整合spring邮箱starter

DBC 1.6K 0
温馨提示

先去网易创建一个邮箱,然后把下面的都开启了,获取代码

邮件发送介绍和项目整合spring邮箱starter插图

首先加入pom文件

   <!--发送邮件-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
配置文件内容
  #邮箱服务配置
  mail:
    host: smtp.126.com #发送邮件服务器
    username: mll17776494600@126.com #发送邮件的邮箱地址
    password: 123123123#客户端授权码,不是邮箱密码,网易的是自己设置的
    from: mll17776494600@126.com # 发送邮件的地址,和上面username一致

    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true
    default-encoding: utf-8

密码是这个

邮件发送介绍和项目整合spring邮箱starter插图2
老规矩,Spring的一个service,一个impl

public interface MailService {

    /**
     * 发送邮件
     * @param to
     * @param subject
     * @param content
     */
    void sendMail(String to,String subject, String content);
}
import lombok.extern.slf4j.Slf4j;
import net.xdclass.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
@Slf4j
public class MailServiceImpl implements MailService {

    /**
     *  springboot 提供的一个发送邮件的简单抽象,直接注入即可
     */
    @Autowired
    private JavaMailSender mailSender;


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

    /**
     * 发送邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    @Override
    public void sendMail(String to, String subject, String content) {

        //创建一个邮箱消息对象
        SimpleMailMessage message = new SimpleMailMessage();

        //配置邮箱发送人
        message.setFrom(from);

        //邮件的收件人
        message.setTo(to);

        //邮件的主题
        message.setSubject(subject);

        //邮件的内容
        message.setText(content);

        mailSender.send(message);

        log.info("邮件发送成功:{}",message.toString());

    }
}
最后一个测试类
import lombok.extern.slf4j.Slf4j;
import net.xdclass.UserApplicacation;
import net.xdclass.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(classes = UserApplicacation.class)
@Slf4j
public class MailTest {
    @Autowired
    private MailService mailService;

    @Test
    public void testSendMail(){
        mailService.sendMail("957955071@qq.com","欢迎注册我的软件","这里是内容");
    }
}
温馨提示

哈哈哈,可以看到成功了

邮件发送介绍和项目整合spring邮箱starter插图4

发表评论 取消回复
表情 图片 链接 代码

分享