首页 > 学院 > 开发设计 > 正文

JAVA实现发送电子邮件

2019-11-14 14:53:51
字体:
来源:转载
供稿:网友

  相信大家对于网站也好,手机app也好,用户注册时,需要进行邮箱验证的功能特别好奇吧,本篇我将带领大家一起实现一下这个简单而又神奇的小功能,让我们的应用也可以加入这些神奇的元素。废话不多说,下面开始我们今天的内容介绍。

  首先实现上面的功能,需要一个固定的发送电子邮件的邮箱地址,这里我们就以我们经常使用的QQ邮箱为例实现一下这个功能。

  第一件事,你需要开启QQ邮箱的IMAP/SMAP服务:

  登录QQ邮箱-->设置-->账号-->开启IMAP/SMAP与P0P3/SMAP

  

  

  

  开启这两个时,你会获得两个密码,接下来的内容中会使用到。

  发送电子邮件服务,需要使用到一下三个JAR包:mail.jar;activation.jar;cos.jar,这里我已经帮大家整理好了,下载地址:http://pan.baidu.com/s/1sknsZOp,下载好我们的JAR包,导入到我们工程的lib目录下即可。

  发送电子邮件的java代码如下:

import java.util.PRoperties;import javax.mail.*;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;/** * 使用QQ邮箱IMAP/SMTP的实现发送电子邮件 * 2015-12-06 */public class Mail {    public static void main(String[] args) {        Properties props = new Properties();        props.put("mail.smtp.host", "smtp.qq.com");        props.put("mail.smtp.port", "587");//使用465或587端口        props.put("mail.smtp.auth", "true");//设置使用验证        props.put("mail.smtp.starttls.enable","true");//使用 STARTTLS安全连接        try {            PopupAuthenticator auth = new PopupAuthenticator();            session session = Session.getInstance(props, auth);            session.setDebug(true);//打印Debug信息            MimeMessage message = new MimeMessage(session);            Address addressFrom = new InternetAddress(PopupAuthenticator.mailuser + "@qq.com", "");//第一个参数为发送方电子邮箱地址;第二个参数为发送方邮箱地址的标签            Address addressTo = new InternetAddress("xxxxxxxxxxxx", "");//第一个参数为接收方电子邮箱地址;第二个参数为接收方邮箱地址的标签            message.setSubject("发送电子邮件的主题");            message.setText("发送电子邮件内容");            message.setFrom(addressFrom);            message.addRecipient(Message.RecipientType.TO, addressTo);            message.saveChanges();            Transport transport = session.getTransport("smtp");            transport.connect("smtp.qq.com", PopupAuthenticator.mailuser, PopupAuthenticator.passWord);            transport.send(message);            transport.close();            System.out.println("发送成功");        } catch (Exception e) {            System.out.println(e.toString());            System.out.println("发送失败");        }    }}class PopupAuthenticator extends Authenticator {    public static final String mailuser = "1453296946";//发送方邮箱'@'符号前的内容:1453296946@qq.com    public static final String password = "xxxxxxxxxxxx";//成功开启IMAP/SMTP服务,在第三方客户端登录时,腾讯提供的密码。注意不是邮箱密码    public PasswordAuthentication getPasswordAuthentication() {        return new PasswordAuthentication(mailuser, password);    }}

  是不是很简单,接下来我们的邮箱验证、登录验证、注册验证、找回密码是不是都找到实现的方向啦。


上一篇:JPA(5)使用二级缓存

下一篇:增强For循环

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表