1.JavaMail的介绍
1.1 什么是JavaMail
JavaMail,提供给开发者处理电子邮件相关的编程接口。它是Sun发布的用来处理email的API。它可以方便地执行一些常用的邮件传输。我们可以基于JavaMail开发出类似于Microsoft Outlook的应用程序。
1.2 JavaMail的应用
注册时发送帐户激活邮件、忘记密码时的账户验证、网站活动通知邮件等。
2. 邮件收发协议
2.1 SMTP
Simple Mail Transfer Protocol,即简单电子邮件协议。
Smtp服务的任务是基于配置接收和发送消息,通常把处理用户SMTP请求(邮件发送请求)的邮件服务器称之为SMTP服务器。
2.2 POP3
Post Office Protocol – Version 3,即“邮局协议版本3”。
POP3协议主要用于支持使用客户端远程管理在服务器上的电子邮件,POP3服务器则是处理邮件接收请求(POP3)。
3.邮件收发的过程
4.邮件发送案例
这里我写一个小Demo,这里贴出MailUtils的代码,如需完整代码请到我的github下载:
https://github.com/honhong/JavaProject/tree/master/maildemo
代码部分:
/**
* 发送邮件的方法
* @param to 邮箱地址
* @param msg 发送的信息
*/
public static void sendMail(String to, String msg) throws Exception {
// 1.创建连接对象,连接到邮箱服务器
Properties prop = new Properties();
// 设置邮件服务器主机名
prop.setProperty("mail.host", host);
// 发送邮件协议名称
prop.setProperty("mail.transport.protocol", "smtp");
// 发送服务器需要身份验证
prop.setProperty("mail.smtp.auth", "true");
/*
注意:使用qq邮箱发送需要开启ssl加密
*/
/*
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.setProperty("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
*/
Session session = Session.getInstance(prop, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
//设置发送人的帐号和密码
return new PasswordAuthentication(from[0], from[1]);
}
});
// 2.创建邮件对象
Message message = new MimeMessage(session);
// 2.1 设置发件者
message.setFrom(new InternetAddress(from[0]));
// 2.2 设置收件者
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
// 2.3 设置邮件主题
message.setSubject("欢迎您注册我们网站");
// 2.4 设置邮件的正文
message.setContent("<h1>请点击<a href='http://localhost:8080/maildemo/ActiveServlet?uid="+msg+"'>此链接</a>以激活账号</h1>", "text/html;charset=utf-8");
// 3.发送邮件
Transport.send(message);
}
演示:
输入注册邮箱及其其它信息并点击注册:
网页跳转提示成功,对应的邮箱也会提示收到新邮件(这里我使用的是qq邮箱,也测试过163)
注意:作为邮件的发送者邮箱需要开启POP3服务。