java 邮件(邮箱)发送代码整理

pom依赖

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

EmailController 代码

package com.ruoyi.web.controller.email;


import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.EmailConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.control.dto.EmailEntityDTO;
import com.ruoyi.control.utils.EmailUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/system/email")
public class EmailController {

    @Resource
    EmailUtils emailUtils;

    @Autowired
    private RedisCache redisCache;

    //   /system/email/sendEmail
    @RepeatSubmit()
    @PostMapping("/sendEmail")
    public AjaxResult verifyEmail(@RequestBody EmailEntityDTO emailEntity) {
        if(StringUtils.isBlank( emailEntity.getSendTo() ) ){
            return AjaxResult.error("收件人不能为空");
        }

        Random random = new Random();
        int randomNumber = random.nextInt(10000);
        while (randomNumber < 1000) {
            randomNumber = random.nextInt(10000);
        }
        String code = String.valueOf(randomNumber);
        String verifyKey = EmailConstants.Email_CODE + emailEntity.getSendTo();
        redisCache.setCacheObject(verifyKey,  code , Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        String detail  = "您的邮件验证码为:" + code  + "用于绑定邮箱身份验证,2分钟内有效,请勿泄露和转发。";
        emailEntity.setDetail(detail);
        emailEntity.setTitle( "验证码" );
        return emailUtils.sendSimpleMail(emailEntity);
    }




}

EmailUtils 发送工具

package com.ruoyi.control.utils;


import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.control.dto.EmailEntityDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class EmailUtils {

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

    @Autowired
    JavaMailSender mailSender;


    public AjaxResult sendSimpleMail(EmailEntityDTO emailEntity) {
        try {
            MimeMessage mailMessage=mailSender.createMimeMessage();
            MimeMessageHelper helper=new MimeMessageHelper(mailMessage,true, Constants.UTF_8);
            //设置寄件人
            helper.setFrom(username);
            //设置收件人
            helper.setTo(emailEntity.getSendTo());
            //设置邮件标题
            helper.setSubject(emailEntity.getTitle());
            //设置邮件内容
            helper.setText(emailEntity.getDetail());
            mailSender.send(mailMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return AjaxResult.success("邮件发送成功");
    }


}


常量

public class EmailConstants {
    public static final String Email_CODE = "emailCode:";
}

DTO

package com.ruoyi.control.dto;

import lombok.Data;

@Data
public class EmailEntityDTO {
    private String sendTo;  //收件邮箱
    private String title;   //邮箱标题
    private String detail;  //邮箱内容
}

配置文件

# Spring配置
spring:
  mail: #邮箱  163 邮箱
    default-encoding: UTF-8
    host: smtp.163.com
    username: lo...k...@163.com
    password: HMMCWMHGR

邮箱配置

 需要获取验证,验证后能获取授权密码

企业端163

灵犀办公免费版-邮件(网易企业邮箱)  url: https://mailh.qiye.163.com/

点击开启按钮,获取授权码

配置信息
default-encoding: UTF-8
host: smtphz.qiye.163.com
username: 自己的邮箱地址
password: 获取的授权码

spring:
  mail: #邮箱
    default-encoding: UTF-8
    host: smtphz.qiye.163.com
    username: .......esmail.com
    password: yd6K..........

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好,以下是 Java 发送定时邮件代码示例: ```java import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class EmailScheduler { public static void main(String[] args) { // 收件人的电子邮件 ID String to = "receiver@example.com"; // 发件人的电子邮件 ID String from = "sender@example.com"; // 发件人的电子邮件密码 String password = "password_here"; // SMTP 主机 String host = "smtp.qq.com"; // 获取系统的属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("mail.smtp.host", host); // 使用 TLS(Transport Layer Security)加密传输 properties.put("mail.smtp.starttls.enable", "true"); // 设置邮件服务器需要授权认证 properties.setProperty("mail.smtp.auth", "true"); // 获取默认的 Session 对象 Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); try { // 创建一个默认的 MimeMessage 对象并设置相关属性 MimeMessage message = new MimeMessage(session); // 设置发件人 message.setFrom(new InternetAddress(from)); // 设置收件人 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置邮件主题 message.setSubject("Test Email from Java"); // 设置邮件正文 message.setText("Hello, this is a test email sent from Java."); // 设置定时时间 Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 10); calendar.set(Calendar.MINUTE, 30); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); Date time = calendar.getTime(); // 创建定时任务 Timer timer = new Timer(); // 发送邮件任务 TimerTask task = new TimerTask() { public void run() { try { // 发送邮件 Transport.send(message); System.out.println("Email sent successfully."); } catch (MessagingException e) { System.out.println("Error occurred while sending email. " + e.getMessage()); } } }; // 定时发送邮件 timer.schedule(task, time); } catch (MessagingException e) { System.out.println("Error occurred while preparing email. " + e.getMessage()); } } } ``` 希望这个代码可以帮到您。如有其他问题,欢迎随时问我。而当您问我前面对我说了什么时,我可以告诉您一个笑话。为什么熬夜对皮肤不好?因为你的脸似乎很喜欢黏键盘。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值