SpringBoot邮件发送

SpringBoot邮件发送

实现的是一个注册的邮箱注册功能,调用接口会向用户的邮箱发送验证码邮件

1.email实体类

package com.jacob.pojo;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class Email {

    @ApiModelProperty(value = "发件人名称")
    private String senderName;

    @ApiModelProperty(value = "发件人邮箱")
    private String senderMail;

    @ApiModelProperty(value = "收件人邮箱")
    private String addresseeMail;

    @ApiModelProperty(value = "邮件标题")
    private String mailTitle;

    @ApiModelProperty(value = "邮件内容")
    private String content;

    @ApiModelProperty(value = "抄送人")
    private String cc[];

    //内容为文本
    private Boolean html = false;

}

2.EmailService接口

package com.jacob.service;

import com.jacob.pojo.Email;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;

@Service
public interface EmailService {

    //发送邮件
    boolean sendMail(Email email) throws MessagingException, UnsupportedEncodingException;
}

3.EmailServicelmpl接口实现类

package com.jacob.service.impl;

import com.jacob.pojo.Email;
import com.jacob.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

@Service
public class EmailServicelmpl implements EmailService {

    @Autowired
    JavaMailSender javaMailSender;
    /*
    官方文档示例
        mailSender.send(new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws MessagingException {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
                message.setFrom("me@mail.com");
                message.setTo("you@mail.com");
                message.setSubject("my subject");
                message.setText("my text <img src='cid:myLogo'>", true);
                message.addInline("myLogo", new ClassPathResource("img/mylogo.gif"));
                message.addAttachment("myDocument.pdf", new ClassPathResource("doc/myDocument.pdf"));
            }
        });
     */

    @Override
    public boolean sendMail(Email email){

        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = null;
        try {
            messageHelper = new MimeMessageHelper(message, true);
            //发件人地址
            InternetAddress fromaddress = new InternetAddress(MimeUtility.encodeText(email.getSenderName()) + "<" + email.getSenderMail() + ">");
            messageHelper.setFrom(fromaddress);

            //收件人地址
            InternetAddress toaddress = new InternetAddress(MimeUtility.encodeText(email.getAddresseeMail()) + "<" + email.getAddresseeMail() + ">");
            messageHelper.setTo(toaddress);

            //邮件主题
            messageHelper.setSubject(email.getMailTitle());

            //setText(内容,是否以html的形式展示)
            messageHelper.setText(email.getContent(),email.getHtml());

            // 测试图片附件(ClassPathResource要把图片放到resources,并且编译代码把图片加载到target里)
            //messageHelper.addInline("myLogo", new ClassPathResource("WechatIMG2602.jpeg"));

            //抄送人
            if(email.getCc()!=null&&email.getCc().length>0){
                messageHelper.setCc(email.getCc());
            }
            javaMailSender.send(message);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}


4.EmailController

package com.jacob.controller;

import com.jacob.pojo.Email;
import com.jacob.service.EmailService;
import com.jacob.utils.commonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import java.util.Random;

@ResponseBody
@Controller
public class EmailController {

    @Autowired
    private EmailService emailService;

    @PostMapping("/emailcode")
    public String sendEmailCode(@RequestParam("emailaddress") String emailaddress, Model model) throws MessagingException, UnsupportedEncodingException {
        //思路就是随机生成验证码,然后把验证码通过邮箱发送出去,最后用户点击注册按钮时验证正确性
        //随机生成的四位验证码
        String randomCode = randomCode();
        Email email = new Email();
        email.setSenderMail("xxxxxxxxx@xxx.com");
        email.setSenderName("博客论坛管理员");
        email.setAddresseeMail(emailaddress);
        email.setMailTitle("博客论坛");
        email.setContent("你正在博客论坛进行账号注册,您的注册码为"+randomCode+",当前时间为"+ commonUtils.getTime().toString());
        boolean sentEmail = emailService.sendMail(email);
        if(sentEmail){
            return randomCode;
        }
        return "发送失败";
    }

    /**
     * 随机生成4位数的验证码
     * @return String code
     */
    private String randomCode(){
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }
}

5.yml配置文件

  mail:
    host: smtp.xxx.com
    username: xxxxxx@xxx.com
    password: xxxxxxxxxxxxxx
    port: 465
    default-encoding: UTF-8
    protocol: smtps
    properties:
      smtp:
        starrtls:
          enable: true
          required: true
        ssl:
          enable: true

6.前端:

//邮件验证码发送
    var returncode = "";
    $("#sentcode").click(function() {
        var mail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
        let mailaddress = $("#mail").val();
        console.log(mailaddress);
        let number = 30;
        let interval = setInterval(Countdown,1000);
        function Countdown(){
            $("#sentcode").attr("disabled",true).val(number+" S");
            // $("#sentcode").val("请"+number+"秒后重新发送");
            if(number==0){
                $("#sentcode").val("获取验证码").removeAttr("disabled");
                clearInterval(interval);
            }
            number--;
        }
        if (mailaddress !== "" && mail.exec(mailaddress)) {
            $.ajax({
                url: "/emailcode",
                data: {"emailaddress":mailaddress},
                type: "post",
                success: function (res) {
                    //判断,返回失败
                    if (res == 'false') {
                        $("#mailbox").css("color","#ff0000").html("验证码获取失败,请稍后重试");
                        $("#sentcode").val("获取验证码").removeAttr("disabled");
                    } else {
                        $("#mailbox").css("color","#1E90FF").html("验证码发送成功");
                        flag = 2;
                        }
                    }
                });
            }
        }
    )
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你好!关于Spring Boot邮件发送,你可以按照以下步骤进行操作: 1. 添加相关依赖:在你的Spring Boot项目的pom.xml文件中,添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 2. 配置邮件服务器:在你的application.properties或者application.yml文件中,添加以下邮件服务器配置信息: ```properties spring.mail.host=your-smtp-hostname spring.mail.port=your-smtp-port spring.mail.username=your-username spring.mail.password=your-password ``` 确保将上述配置信息替换为你自己的邮件服务器的相关信息。 3. 创建邮件发送服务类:创建一个邮件发送服务类,用于构建和发送邮件。你可以使用Spring Boot提供的JavaMailSender接口来完成这个任务。以下是一个简单的示例: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; @Service public class EmailService { @Autowired private JavaMailSender mailSender; public void sendEmail(String to, String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(text); mailSender.send(message); } } ``` 4. 调用邮件发送服务:在需要发送邮件的地方,注入邮件发送服务类,并调用sendEmail方法发送邮件。以下是一个简单的示例: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class EmailController { @Autowired private EmailService emailService; @GetMapping("/sendEmail") public String sendEmail() { String to = "recipient@example.com"; String subject = "Test Email"; String text = "This is a test email."; emailService.sendEmail(to, subject, text); return "Email sent successfully!"; } } ``` 请根据你的实际需求进行适当的修改和扩展。希望能对你有所帮助!如果还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值