java发送验证码

导入maven包(commons-email)

<dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-email</artifactId>
      <version>1.5</version>
</dependency>

 

以邮箱发送注册验证码

public void sendEmail(String toEmail, String fromEmail, String code)
    {
        HtmlEmail email=new HtmlEmail();//创建email对象
        email.setCharset("UTF-8");//设置UTF-8字符编码
        email.setHostName("smtp.163.com");//设置发送服务器(以网易邮箱为例子)
        try {
            email.addTo(toEmail);
            email.setFrom(fromEmail,"xiaoxing");
            email.setAuthentication(fromEmail,code);
            email.setSubject("注册验证");
            email.setMsg("验证码为:"+getRandomCode(6)+",十分钟内有效。");//设置邮件内容(使用生成验证码函数)
            email.send();//发送邮件
        } catch (EmailException e) {
            System.out.println("发送失败"+e.getMessage());
        }
    }

生成验证码

public static String getRandomCode(int n)
    {
        Random random=new Random();
        StringBuilder str=new StringBuilder();
        for(int i=0;i<n;i++)
        {
            str.append(random.nextInt(10));
        }
        return  str.toString();
    }

  

posted @ 2023-03-21 11:00  xiaoxing~  阅读(60)  评论(0)    收藏  举报