通过 Java 配置企业邮箱发送验证码邮件

通过 Java 配置企业邮箱发送验证码邮件

配置企业邮箱 SMTP 服务

示例使用腾讯企业邮箱:腾讯企业邮箱,进入邮箱设置中,收发信设置中开启SMTP服务
在这里插入图片描述
同时这里可以看到要使用的host以及端口
在这里插入图片描述

进入邮箱绑定,生成一个新密码
在这里插入图片描述

之后进入我们的maven项目中添加javamail的依赖

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

同时在yml文件中进行配置操作

mail:
  host: smtp.exmail.qq.com
  username: 你的邮箱名
  password: 生成的密码
  port: 465
  protocol: smtp
  properties:
    mail:
      smtp:
        ssl:
          enable: true
          required: false
        debug: true

编写一个发送邮件的工具类

/**
 *邮件发送工具类(图片、附件均为可选)
*/
@Component
public classMailUtil {

    @Value("${mail.host}")
privateString host;

    @Value("${mail.username}")
privateString username;

    @Value("${mail.password}")
privateString password;

    @Value("${mail.port}")
privateString port;

/**
     *发送邮件
*
     *@paramto接收人邮箱
*@paramsubject邮件标题
*@paramcontent邮件正文内容
*@paramimagePath邮件内嵌图片路径(可选)
*@paramattachmentPath邮件附件路径(可选)
*@throwsException
*/
public voidsendMail(String to, String subject, String content, String imagePath, String attachmentPath)throwsException {

        Properties props =newProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.required", "false");
        props.put("mail.smtp.debug", "true");

        Session session = Session.getInstance(props);
        session.setDebug(true);

        MimeMessage message =newMimeMessage(session);

        message.setFrom(newInternetAddress(username, "Tianwailaiwu", "UTF-8"));
        message.addRecipient(Message.RecipientType.TO,newInternetAddress(to, "收件人昵称", "UTF-8"));
        message.setSubject(subject, "UTF-8");

// ----正文部分 ----
MimeBodyPart textPart =newMimeBodyPart();
if(imagePath !=null&& !imagePath.isEmpty()) {
            textPart.setContent(content + "<br/><img src='cid:image001'/>", "text/html;charset=UTF-8");
        }else{
            textPart.setContent(content, "text/html;charset=UTF-8");
        }

// ----图片部分(可选) ----
MimeMultipart textImageMultipart =newMimeMultipart();
        textImageMultipart.addBodyPart(textPart);

if(imagePath !=null&& !imagePath.isEmpty()) {
            MimeBodyPart imagePart =newMimeBodyPart();
            imagePart.setDataHandler(newDataHandler(newFileDataSource(imagePath)));
            imagePart.setContentID("image001");
            textImageMultipart.addBodyPart(imagePart);
        }

        textImageMultipart.setSubType("related");

        MimeBodyPart contentPart =newMimeBodyPart();
        contentPart.setContent(textImageMultipart);

MimeMultipart allMultipart =newMimeMultipart();
        allMultipart.addBodyPart(contentPart);

if(attachmentPath !=null&& !attachmentPath.isEmpty()) {
            MimeBodyPart attachmentPart =newMimeBodyPart();
            attachmentPart.setDataHandler(newDataHandler(newFileDataSource(attachmentPath)));
            attachmentPart.setFileName(MimeUtility.encodeText("附件.doc"));
            allMultipart.addBodyPart(attachmentPart);
        }

        allMultipart.setSubType("mixed");

        message.setContent(allMultipart);
        message.setSentDate(newDate());
        message.saveChanges();

        Transport transport = session.getTransport();
        transport.connect(username, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }
}

其中图片以及附件是作为可选项的,如果不需要可以设置为null

发送邮件测试

@RestController
public class MailTest {

    private final MailUtil mailUtil;

    @Autowired
    public MailTest(MailUtil mailUtil){
        this.mailUtil=mailUtil;
    }

    @PostMapping("/mail")
    public void sendMail(String email){
        try {
            mailUtil.sendMail(
                    email,
                    "emailTest",
                    "123456",
                    null,
                    null
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

请求之后发送成功

40393612b25c4848aa140097200c6d9.jpg

更改发送排版

要使发送的邮箱排版更加美观,我们可以使用HTML对正文进行排版以及CSS来进行调整

更改如下:

mailUtil.sendMail(
        email,
        "MailTest - 验证码",
        "<html>" +
                "<body style='font-family: Arial, sans-serif; padding: 20px; background-color: #f4f4f4;'>" +
                "<div style='max-width: 600px; margin: 0 auto; background-color: #ffffff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);'>" +
                "<h2 style='color: #333333;'>你好,欢迎使用 MailTest!</h2>" +
                "<p style='font-size: 16px; color: #555555;'>你的验证码为:<strong style='color: #0066cc;'>123124</strong></p>" +
                "<p style='font-size: 14px; color: #888888;'>验证码有效期为 5 分钟,请及时使用。</p>" +
                "<p style='font-size: 14px; color: #888888;'>如果你没有进行此操作,请忽略此邮件。</p>" +
                "<hr style='border-top: 1px solid #eeeeee;'/>" +
                "<footer style='font-size: 12px; color: #888888; text-align: center;'>" +
                "<p>MailTest团队 &copy; 2025</p>" +
                "</footer>" +
                "</div>" +
                "</body>" +
                "</html>",
null,
null
);

效果如下:

5cd2bb6e1998e3acff6c65b76f3e401.jpg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值