最近写项目用到JSP发送邮件的功能,找了一下资料,其实也挺简单。首先,需要两个jar包库,
JavaMail:下载地址:http://www.oracle.com/technetwork/java/index-138643.html
JavaBeans Activation Framework(JAF):下载地址:http://www.oracle.com/technetwork/java/javase/jaf-136260.html
下载解压后,将会看到一系列jar包。将mail.jar包和activation.jar包加入CLASSPATH变量中,或者直接将解压后的所有jar包拷贝到
tomcat的lib文件夹下,刷新eclipse,重启tomcat即可,下面是源代码:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ page import="java.io.*,java.util.*,javax.mail.*"%> <%@ page import="javax.mail.internet.*,javax.activation.*"%> <%@ page import="javax.servlet.http.*,javax.servlet.*"%> <% class MyAuthenticator extends javax.mail.Authenticator { private String strUser; private String strPwd; public MyAuthenticator(String user, String password) { this.strUser = user; this.strPwd = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(strUser, strPwd); } } String result; //邮件发送的结果 String to = "2********[email protected]"; // 收件人的电子邮件 String from = "1*******[email protected]"; // 发件人的电子邮件 String host = "smtp.163.com"; // 发送电子邮件的主机,这里利用163邮箱做中介,在邮箱设置中可以设置smtp,找到SMTP的相关主机名 Properties properties = System.getProperties(); // 获取系统属性对象 properties.setProperty("mail.smtp.host", host); // 设置邮件服务器 // Session mailSession = Session.getDefaultInstance(properties); // 获取默认的Session对象。 properties.put("mail.smtp.auth", "true"); MyAuthenticator authentic = new MyAuthenticator("你所做主机的163邮箱的账号","账号密码"); Session mailSession = Session.getDefaultInstance(properties,authentic); try { MimeMessage message = new MimeMessage(mailSession); // 创建一个默认的MimeMessage对象。 message.setFrom(new InternetAddress(from)); // 设置 From: 头部的header字段 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置 To: 头部的header字段 message.setSubject("This is the Subject Line!"); // 设置 Subject: header字段 message.setText("This is actual message"); // 现在设置的实际消息 Transport.send(message); // 发送消息 result = "发送邮件成功...."; } catch (MessagingException mex) { mex.printStackTrace(); result = "Error: unable to send message...."; } %> <html> <head> <title>发送邮件</title> </head> <body> <center> <h1>发送邮件</h1> </center> <p align="center"> <% out.println("Result: " + result + "\n"); %> </p> </body> </html>上面163的SMTP具体设置见:http://blog.csdn.net/u014267402/article/details/40684833 中的第一步。
本人经验,仅供参考!