Springboot简单的邮箱发送程序

1. 开启以下服务,并获取其授权码作为客户端的登录密码

在这里插入图片描述
或者其他邮箱同理

2. 创建springboot项目,导入email相关的依赖
        <!--导入email辅助包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
3.在yml或properties配置文件配置需要的配置
    #邮箱配置
  mail:
    protocol: smtp
    host: smtp.qq.com
    port: 587
    username: xxxxxx@qq.com
    password: xxxxxxxxx
    default-encoding: utf-8
    properties:
      mail:
        debug: true #会完整的打印邮箱的日程日志
        smtp:
          connectiontimeout: 5000
          timeout: 3000
          writetimeout: 5000
4.创建简单的邮件发送工具类或者业务层

此为业务层实例

import xxx.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSendException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("emailService")
@Transactional(rollbackFor = Exception.class)
public class EmailServiceImpl implements EmailService {
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String from;
    @Override
    public boolean send(String emailAddress, String code) {
        log.info("获取验证码中");
        //定制纯文本邮件信息
        SimpleMailMessage message=new SimpleMailMessage();
          try {
              //qq的smtp发送服务器的名称
              message.setFrom(from);
              //收件人的邮箱
              message.setTo(emailAddress);
              //要发送的邮件主题
              message.setSubject("邮箱认证");
              //邮件的内容
              String content = emailAddress+code;
              message.setText(content);
              javaMailSender.send(message);
              log.info("发送验证码成功");
              return true;
          }catch (MailSendException e){
              e.printStackTrace();
              return false;
          }
    }
}

5. 直接调用以上方法即可
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

锐行织梦者

谢谢您的支持!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值