java实现邮箱注册发送验证码到填写的邮箱

先生成一个  mail的的工具类

package com.zking.TestMail;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author Cy
 * @site www.Cy.com
 * @company Cy公司
 * @create  2019-02-25 18:41
 */
public class MailUtil {

    /**
         * 发送邮件
          * @param to 给谁发
           * @param text 发送内容
          */
     public static void send_mail(String to,String text) throws MessagingException {
                //创建连接对象 连接到邮件服务器
              Properties properties = new Properties();
               //设置发送邮件的基本参数
               //发送邮件服务器(注意,此处根据你的服务器来决定,如果使用的是QQ服务器,请填写smtp.qq.com)
              properties.put("mail.smtp.host", "smtp.qq.com");
              //发送端口(根据实际情况填写,一般均为25)
               properties.put("mail.smtp.port", "25");
                 properties.put("mail.smtp.auth", "true");
              //设置发送邮件的账号和密码
               Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                              //两个参数分别是发送邮件的账户和密码(注意,如果配置后不生效,请检测是否开启了 POP3/SMTP 服务,QQ邮箱对应设置位置在: [设置-账户-POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务])
                              return new PasswordAuthentication("[email protected]","你的pop3开启时生成的密码");
                           }
         });

               //创建邮件对象
                Message message = new MimeMessage(session);
              //设置发件人
               message.setFrom(new InternetAddress("[email protected]"));
               //设置收件人
               message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
              //设置主题
               message.setSubject("这是一份测试邮件");
                //设置邮件正文  第二个参数是邮件发送的类型
              message.setContent(text,"text/html;charset=UTF-8");
             //发送一封邮件
              Transport.send(message);
       }
 }

在创建测试类测试:

package com.zking.TestMail;

import javax.mail.MessagingException;

/**
 * @author Cy
 * @site www.Cy.com
 * @company Cy公司
 * @create  2019-02-25 18:46
 */
public class MailTest {
    public static void main(String[] args) {
        try {
      // 请将此处的 ******@qq.com 替换为您的收件邮箱号码
            MailUtil.send_mail("******@qq.com", "您的注册验证码为:254685");
            System.out.println("邮件发送成功!");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

注意此处:   

   @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                              //两个参数分别是发送邮件的账户和密码(注意,如果配置后不生效,请检测是否开启了 POP3/SMTP 服务,QQ邮箱对应设置位置在: [设置-账户-POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务])
                              return new PasswordAuthentication("[email protected]","你的pop3开启时生成的密码");
                           }
         });
这里第二个参数一定要填写你开启pop3时生成的密码(不要填邮箱的登录密码)。不然会报如下的错:

java实现邮箱注册发送验证码到填写的邮箱
 

如出现此错误,把第二个参数密码改为pop3的密码