邮箱验证码发送

图片验证码

展示

首先生成图片通过HTTP响应输出到前端页面中,并在session的Attribute中设置code,以便后续输入的和session的key进行对比

@RequestMapping("/checkCode")
//HttpSession用于存储和获取会话数据
public void checkCode(HttpServletResponse response, HttpSession session, Integer type) throws
       IOException {
    CreateImageCode vCode = new CreateImageCode(130, 38, 5, 10);
    //设置响应头
    response.setHeader("Pragma", "No-cache");
    //
    response.setHeader("Cache-Control", "no-cache");
    //不会被缓存
    response.setDateHeader("Expires", 0);
    //输出的是一个图片
    response.setContentType("image/jpeg");
    //生成验证码
    String code = vCode.getCode();
    System.out.println("code:" + code);
    if (type == null || type == 0) {
       //存储在名为CHECK_CODE_KEY的键中,值为code
       session.setAttribute(Constants.CHECK_CODE_KEY, code);
    } else {
       session.setAttribute(Constants.CHECK_CODE_KEY_EMALL, code);
    }
    // 将生成的验证码图片写入HTTP响应输出流
    vCode.write(response.getOutputStream());
}

发送邮箱验证码

通过使用javaMailSender通过qq邮箱提供的STMP服务,向指定的邮箱发送随机生成的验证码

配置:

spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=test@qq.com
spring.mail.password=
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true

主要设置的就是pwd和用户名,可以去百度教程找一下如何配置这两个

controller层

//发送邮箱验证码
@RequestMapping("/sendEmailCode")
@GlobalInterceptor(checkParams = true, checkLogin = false)
public ResponseVO sendEmailCode(HttpSession session,
                         @VerifyParam(required = true, regex = VerifyRegexEnum.EMAIL, max = 150) String email,
                         @VerifyParam(required = true) String checkCode,
                         @VerifyParam(required = true) Integer type) throws BusinessException {
    try{
       if (!checkCode.equalsIgnoreCase((String) session.getAttribute(Constants.CHECK_CODE_KEY_EMALL))) {
          throw new BusinessException("图片验证码不正确");
       }
       //调用emailCodeService中的sendEmailCode方法发送邮件验证码
       emailCodeService.sendEmailCode(email, type);
       return getSuccessResponseVO(null);
    } finally {
       //从会话中移除CHECK_CODE_KEY_EMALL属性
       session.removeAttribute(Constants.CHECK_CODE_KEY_EMALL);
    }
}

1. 先验证图片验证码是否正确

2.发送图片验证码

EmailCodeServicelmpl层

@Override
//声明方法的事务属性,遇到Exception时回滚
@Transactional(rollbackFor = Exception.class)
public void sendEmailCode(String email, Integer type) throws BusinessException {
    if(type==0){
       //根据邮箱查询用户信息
       UserInfo userInfo = userInfoMapper.selectByEmail(email);
       if(null!=userInfo){
          throw new BusinessException("邮箱已经存在");
       }
    }
    //生成一个随机的五位数字验证码
    String code = StringTools.getRandomNumber(Constants.LENGTH_5);

    //重写方法,调用重写的sendEmailCode,向邮箱发送验证码
    sendEmailCode(email, code);

    //将之前的验证码都值为无效
    emailCodeMapper.disableEmailCode(email);

    EmailCode emailCode = new EmailCode();
    emailCode.setCode(code);
    emailCode.setEmail(email);
    //设置状态为未使用
    emailCode.setStatus(Constants.ZERO);
    //设置创建时间为当前时间
    emailCode.setCreateTime(new Date());
    //插入新的EmailCode对象到数据库中
    emailCodeMapper.insert(emailCode);
}

1.随机生成验证码

2.向指定邮箱生成验证码。

3.使得先前生成的验证码都无效

4.将code插入数据库中

发送验证码真正的逻辑:

private void sendEmailCode(String toEmail, String code) {
    try{
       //创建一个新的MinMessage
       MimeMessage message = javamailSender.createMimeMessage();
       //使用mimeMessageHelper来简化创建复杂的MimeMessage
       MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message);
       //设置邮箱发送者
       mimeMessageHelper.setFrom(appConfig.getSendUserName());
       //设置邮箱的接收者
       mimeMessageHelper.setTo(toEmail);
       //从Redis缓存中的系统设置
       SysSettingsDto sysSettingsDto = redisComponent.getSysSettingsDto();

       //设置标题
       mimeMessageHelper.setSubject(sysSettingsDto.getRegisterMailTitle());
       //设置内容
       mimeMessageHelper.setText(String.format(sysSettingsDto.getRegisterEmailContent(), code));
       mimeMessageHelper.setSentDate(new Date());

       javamailSender.send(message);

    }catch (Exception e){
       logger.error("邮件发送失败", e);
           try {
               throw new BusinessException(e.getMessage());
           } catch (BusinessException ex) {
               throw new RuntimeException(ex);
           }
       }

disableEmailCode:

emailCodeMapper.disableEmailCode(email);

xml层:

update email_code set status 1 where email = #{email} and status = 0

### 回答1: 您好,关于Java邮箱验证码发送的问题,我可以回答。 要发送邮箱验证码,需要使用JavaMail API,它是Java语言的邮件协议的一个实现。您需要设置SMTP服务器的地址和端口,并提供发送者和接收者的邮件地址。您可以使用Java代码生成随机数字,并将其作为验证码发送到接收者的邮箱地址。 以下是一个简单的Java代码示例,可以发送邮件验证码: ```java import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Random; public class SendEmail { public static void main(String[] args) { // 邮箱地址和授权码 final String senderEmail = "你的邮箱地址"; final String password = "你的邮箱授权码"; // SMTP服务器地址和端口 String host = "smtp.xxx.com"; int port = 587; // 接收者的邮箱地址 String recipient = "接收者的邮箱地址"; // 生成随机验证码 Random rand = new Random(); int code = rand.nextInt(999999); // 设置邮件属性 Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); // 创建会话对象 Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication(senderEmail, password); } }); try { // 创建邮件消息 Message message = new MimeMessage(session); message.setFrom(new InternetAddress(senderEmail)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient)); message.setSubject("验证码"); message.setText("您的验证码是:" + code); // 发送邮件消息 Transport.send(message); System.out.println("验证码发送到您的邮箱。"); } catch (MessagingException e) { throw new RuntimeException(e); } } } ``` 请注意,您需要将代码中的SMTP服务器地址、端口、发件人邮箱地址和授权码、收件人邮箱地址替换为您自己的信息。 ### 回答2: 在Java中实现邮箱验证码发送可以通过使用JavaMail API来实现。以下是一个简单的例子,展示了如何使用JavaMail API发送验证码: 首先,需要导入JavaMail和javax.mail库: ```java import java.util.Properties; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; ``` 要发送验证码,我们需要一个发送邮件的方法,例如sendVerificationCode: ```java public static void sendVerificationCode(String recipientEmail, String verificationCode) { // 配置SMTP服务器 Properties properties = new Properties(); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", "smtp.example.com"); // 根据实际情况修改 properties.put("mail.smtp.port", "587"); //根据实际情况修改 // 创建Session对象 Session session = Session.getInstance(properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("your_email@example.com", "your_password"); // 根据实际情况修改 } }); try { // 创建MimeMessage对象 Message message = new MimeMessage(session); // 设置发件人和收件人 message.setFrom(new InternetAddress("your_email@example.com")); // 根据实际情况修改 message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail)); // 设置邮件主题和内容 message.setSubject("邮箱验证码"); message.setText("您的验证码是:" + verificationCode); // 发送邮件 Transport.send(message); System.out.println("验证码发送成功"); } catch (MessagingException e) { e.printStackTrace(); } } ``` 在上述代码中,需要修改SMTP服务器地址、端口、发件人邮箱和密码。然后,可以调用该方法来发送验证码给指定的收件人邮箱。 一个使用该方法的例子: ```java public class Main { public static void main(String[] args) { String recipientEmail = "recipient@example.com"; // 收件人邮箱,根据实际情况修改 String verificationCode = "123456"; // 验证码,根据实际情况修改 sendVerificationCode(recipientEmail, verificationCode); } } ``` 以上就是一个简单的使用JavaMail API实现邮箱验证码发送的例子。当然,在实际情况下,可能还需要进行一些验证、异常处理等操作来增加程序的健壮性和安全性。 ### 回答3: 在Java发送邮箱验证码需要使用Java Mail API和Java Activation Framework(JAF)来实现。以下是一个简单的示例代码: ```java import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; import java.util.Random; public class EmailVerificationSender { public static void main(String[] args) { String recipientEmail = "recipient@example.com"; // 收件人邮箱地址 // 生成随机验证码 String verificationCode = generateVerificationCode(); // 配置邮件服务器 Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.example.com"); // 邮件服务器主机名 properties.put("mail.smtp.port", "587"); // 邮件服务器端口号 properties.put("mail.smtp.auth", "true"); // 启用身份验证 properties.put("mail.smtp.starttls.enable", "true"); // 启用TLS加密 // 创建邮件会话 Session session = Session.getInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("your_username", "your_password"); } }); try { // 创建邮件消息 Message message = new MimeMessage(session); message.setFrom(new InternetAddress("your_email@example.com")); // 发件人邮箱地址 message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail)); message.setSubject("邮箱验证码"); // 邮件主题 // 设置邮件正文 message.setText("您的验证码是:" + verificationCode); // 发送邮件 Transport.send(message); System.out.println("验证码已成功发送邮箱:" + recipientEmail); } catch (MessagingException e) { e.printStackTrace(); System.out.println("发送邮件时发生错误"); } } // 生成随机验证码的方法 private static String generateVerificationCode() { Random random = new Random(); int code = random.nextInt(900000) + 100000; return String.valueOf(code); } } ``` 请将上述代码中的"smtp.example.com"、"your_username"、"your_password"、"your_email@example.com"和"recipient@example.com"替换为实际的邮件服务器信息、发件人邮箱和收件人邮箱。 这段代码中使用了Java Mail API提供的类来创建邮件和设置邮件内容,通过SMTP协议发送邮件,同时启用了TLS加密来保证邮件传输的安全性。generateVerificationCode()方法生成了一个6位数的随机验证码,作为邮件的正文内容发送给收件人。 此代码可以作为一个简单的Java邮件发送程序参考,并可以根据具体情况进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值