本来一路项目一路顺畅,突然上头来了个邮件验证功能的开发,我也没接触过,很是头疼。
在参考了诸多文档和很多的改动之后终于实现了。
这个功能需要jmail的jar包支持
mail.jar下载:https://www.findjar.com/jar/javax/mail/mail/1.4.1/mail-1.4.1.jar.html
commons-email.jar下载:https://www.findjar.com/index.x?query=commons-email
activation.jar下载:https://www.findjar.com/index.x?query=activation.jar
下载好直接加入项目(当然如果用的maven就没这个事了)
/**
* 发送邮件验证
* @param receiver
* @throws MessagingException
*/
public static String sendMail(String 接收账号,String 发送内容 throws Exception {
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");//设置访问smtp服务器需要认证
props.setProperty("mail.transport.protocol", "smtp"); //设置访问服务器的协议
Session session = Session.getDefaultInstance(props, new Authenticator(){//也可以单独创建Authenticator对象
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("服务器邮箱账号", "密码");
}
});
session.setDebug(true); //打开debug功能
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("发件人账号")); //设置发件人,发件人与登录用户必须一致(必填
//自己封装的获取session的方法,与普通session一致,我这里是用来在controller验证用的
HttpUtil.getHttpSession().setAttribute("mialValue", text);
msg.setText(设置邮件内容 );
msg.setSubject(设置邮件主题);
Transport trans = session.getTransport();
trans.connect("smtp.exmail.qq.com", 25, "账号@之前", "密码"); //邮箱smtp服务器,我这用的是Foxmail,25为默认端口
trans.sendMessage(msg, new Address[]{new InternetAddress(接收人账号 )}); //
trans.close(); //关闭连接
return text;//返回随机数用于验证
}
此段代码可以用于发送验证码啥的。可以作为一个工具类来使用。
注意点就是作为发送服务器的邮箱需要开启发件服务器smtp功能支持才能发出去哦
(为记录成长而写,有误导的地方多包含吧,我是正常使用的,也希望帮到初学者)