现在很多网站的注册过程中,大多数都会让用户用邮箱注册,这也方便用户在忘记登陆密码时,在重设密码时,可以发送链接到该注册时填写的邮箱中,让用户可以链接到密码修改页面,这就少了很多程序。
写这个小案例是为了方便一些想做邮件发送功能,而不知道从什么地方下手的程序员更好的接触javamail是怎样实现这一功能的
第一步,先到https://java.net/projects/javamail/pages/Home#Download_JavaMail_Release下载javax.mail.jar,
http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-eeplat-419426.html#javamail-1.4.5-oth-JPR,下载相关的api文件
第二步:导入一下jar包
javax.mail.jar
mail.jar
mailapi.jar
smtp.jar
第三步:编写测试程序Test.java
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
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;
import com.sun.mail.smtp.SMTPSSLTransport;
public class Test {
public static void main(String[] args) throws MessagingException {
// 配置发送邮件的环境属性
final Properties props = new Properties();
/** 可用的属性: mail.store.protocol / mail.transport.protocol / mail.host /
* mail.user / mail.from*/
// 表示SMTP发送邮件,需要进行身份验证
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.qq.com");
// 发件人的账号也是你在qq邮箱中开启smtp服务的邮箱地址
props.put("mail.user", "*********@QQ.com");
// 访问SMTP服务时需要提供的密码(授权码)
props.put("mail.password", "************");
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
// 设置发件人
InternetAddress form = new InternetAddress(
props.getProperty("mail.user"));
message.setFrom(form);
// 设置收件人
InternetAddress to = new InternetAddress("945763994@QQ.com");
message.setRecipient(RecipientType.TO, to);
// 设置邮件标题
message.setSubject("测试邮件");
// 设置邮件的内容体
message.setContent("<a href='http://www.fkjava.org'>测试的HTML邮件</a>", "text/html;charset=UTF-8");
// 发送邮件
Transport transport = new SMTPSSLTransport(mailSession, null);
//这个步很重要,不能省略
transport.connect("smtp.qq.com",props.getProperty("mail.user"), props.getProperty("mail.password"));
System.out.println(transport.isConnected());
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
}
上面的代码在javaee中的servlet中执行也是可以实现的,因为javamail可以在se和ee框架中使用,想了解更多,可以到官网查看
http://www.oracle.com/technetwork/java/javamail/index.html
我还有一篇有关apache的commons-email的使用,可惜在同样的simpleEmail代码不能在servlet执行而在main方法中可以使用,如果有人解决这个问题的大哥们,请留言告诉小弟。