自己填写class email_inf里的配置,
使用方法:调用achievecode获取一个随机验证码并保存然后通过sendAuthCodeEmail方法发送邮件
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class email {
public String achieveCode() { // 随机验证码
String[] beforeShuffle= new String[] { "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
"G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a",
"b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z" };
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)); //将集合转化为字符串
}
return sb.toString().substring(3, 8); //截取字符串第4到8
}
//发送验证码邮件
public boolean sendAuthCodeEmail(String email, String authCode) {
HtmlEmail mail = new HtmlEmail();
try {
mail.setHostName(email_inf.hostname); //smtp服务器
//如果使用25端口发可以注释下面两行
mail.setSSLOnConnect(true); //使用ssl加密true
mail.setSslSmtpPort("465"); //使用465端口
mail.setCharset(email_inf.charset); //字符集
mail.addTo(email); //收件人邮箱
mail.setFrom(email_inf.setfromemail, email_inf.setfromname); //发送人邮箱,发件人
mail.setAuthentication(email_inf.username, email_inf.userpassword); //用户名,密码(是smtp/pop密码,不是邮箱密码,)
mail.setSubject(email_inf.title); //标题
mail.setMsg(email_inf.msg1+authCode+ email_inf.msg2); //authcode是形参,验证码,上下两个msg、是html可以自己改。
mail.send(); //发送
System.out.println("发送成功");
return true;
} catch (EmailException e) {
e.printStackTrace();
return false;
}
}
}
class email_inf { //这里存储的是配置信息
public final static String hostname=new String("smtp.***.com");// 这里是SMTP发送服务器的名字"
public final static String charset=new String("utf-8");// 字符编码集的设置
public final static String setfromemail=new String("***@***.com");// 发送人的邮箱
public final static String setfromname=new String("***");//发送人
public final static String username=new String("***@***.com");//邮箱用户名
public final static String userpassword=new String("********************");//pop密码
public final static String title=new String("验证码");//邮件主题
public final static String msg1=new String("
尊敬的用户:您好! 您正在进行登录/注册账号操作,请在验证码输入框中输入:");
public final static String msg2=new String(",以完成操作。注意:此操作可能会修改您的密码或登录邮箱。如非本人操作,请及时登录并修改密码以保证帐户安全
(工作人员不会向你索取此验证码,请勿泄漏!)
此为系统邮件,请勿回复
请保管好您的邮箱,避免账号被他人盗用
木辰网络科技团队
");
//邮件内容
}