0
点赞
收藏
分享

微信扫一扫

SpringBoot集成邮件发送


我们在学习了sprinBoot的架构后,肯定需要一些小的操作,比如邮件发送。下面将讲述如何集成163邮箱的邮件服务器。

一:首先是注册网易的邮件服务器

1:首先你登录到网易163邮箱,然后在设置-》POP3/SMTP/IMAP中,点击开通邮箱。

2:输入密码,你自己设置的,要记住。

二:springBoot代码开发

1:引入jar包,在pom.xml里引入如下内容:

<!-- 邮件服务 begin -->

<dependency> 
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

        <!-- 邮件服务 end -->

2:写发送邮箱的配置,在application.properties中添加邮件的一些基本配置:

##//邮箱服务器地址
 spring.mail.host=smtp.163.com
 ##//用户名
 spring.mail.username=XXX@163.com
 ##//密码,你启动163邮箱服务的时候,设置的密码。
 spring.mail.password=XXXX
 spring.mail.default-encoding=UTF-8
 ##以谁来发送邮件,你登录的邮箱。
 mail.fromMail.addr=XX@163.com

3:写公用java类:

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.Component;
 @Component
 public class MailServiceImpl{
    @Autowired
    private JavaMailSender mailSender;


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


    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);


        try {
            mailSender.send(message);
            //logger.info("简单邮件已经发送。");
        } catch (Exception e) {
        e.printStackTrace();
            //logger.error("发送简单邮件时发生异常!", e);
        }


    }}

4:使用邮件服务。

@Autowired
private MailServiceImpl mailServiceImpl;
@RequestMapping(value = "/sendEmail", method = RequestMethod.GET)
public String getUser() {
mailServiceImpl.sendSimpleMail("发送给谁的邮箱", "测试邮箱", "你好这是测试邮箱");
return "sendEmail success";
}

举报

相关推荐

0 条评论