JAVA实现邮箱发送验证码
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailUtils {
/**
11 * 发送邮件
12 * @param to 给谁发
13 * @param text 发送内容
14 */
public static void send_mail(String to,String text) throws MessagingException {
//创建连接对象 连接到邮件服务器
Properties properties = new Properties();
//设置发送邮件的基本参数
//发送邮件服务器 根据发送邮箱的服务器编写
properties.put("mail.smtp.host", "smtp.163.com");
//发送端口
properties.put("mail.smtp.port", "25");
properties.put("mail.smtp.auth", "true");
//设置发送邮件的账号和密码
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//两个参数分别是发送邮件的账户和密码
return new PasswordAuthentication("发件人的邮箱","发件人的邮箱密码");
}
});
//创建邮件对象
Message message = new MimeMessage(session);
//设置发件人
message.setFrom(new InternetAddress("发件人的邮箱"));
//设置收件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
//设置主题
message.setSubject("发送主题");
//设置邮件正文 第二个参数是邮件发送的类型
message.setContent(text,"text/html;charset=UTF-8");
//发送一封邮件
Transport.send(message);
}
}
验证码工具类
public class RandomUtils {
public String getRandom() {
String[] beforeShuffle = new String[] { "1", "2", "3", "4", "5", "6",
"7", "8", "9", "0"};
List list = Arrays.asList(beforeShuffle);
Collections.shuffle(list);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
sb.append(list.get(i));
}
String afterShuffle = sb.toString();
String result = afterShuffle.substring(5, 9);
System.out .print(result) ;
return result;
}
}
测试:
发件人的邮箱
import java.util.Random;
import javax.mail.MessagingException;
import com.cblue.email.utils.EmailUtils;
import com.cblue.email.utils.RandomUtils;
/**
* 测试
* @author lenovo
*
*/
public class EmailTest {
public static void main(String[] args) {
//创建的随机数的工具类,生成验证码
RandomUtils randomUtils = new RandomUtils();
String random = randomUtils.getRandom();
try {
EmailUtils.send_mail("收件人邮箱", "用户您好您的验证码为:"+random);
System.out.println("邮件发送成功!");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
网页题目:JAVA实现邮箱发送验证码
文章地址:http://pwwzsj.com/article/cpheoe.html