JavaMail是Sun发布的用来处理E-mail的API,它可以方便地执行一些常用的邮件传输.不过它并没被加到Java开发工具包(JDK)中,这就意味着在使用前必须另外下载JavaMail,还需要有Sun的JavaBeans Activation Framework(JAF)支持,因此需要下载一个叫activation.jar的文件,将它们同时放在应用的lib目录下或其他Classpath包含的目录.
发送邮件过程中主要使用用到以下几个类:
1.Javax.mail.Session类
2.Javax.mail.Message类
3.Javax.mail.Address类
4.Javax.mail.Transport类
了解了以上几个类后,要用Javamail发送一封普通邮件就变得容易多了.
下面为为一个专门处理邮件的类:
package ch2.util.mail;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.Address;
/**
* @author Administrator
*/
public class MailUtil {
static int port = 25; //smtp端口
static String server = "smtp.126.com"; //smtp服务器地址
static String from = "Webmaster<*@126.com>"; //发送者
static String user = *@126.com; //发送者地址
static String password = "yourPassword"; //密码
public static void sendEmail(String email, String subject, String body) {
try {
Properties props = new Properties();
props.put("mail.smtp.host", server);
props.put("mail.smtp.port", String.valueOf(port));
props.put("mail.smtp.auth", "true");
Transport transport = null;
Session session = Session.getDefaultInstance(props, null);
transport = session.getTransport("smtp");
transport.connect(server, user, password);
MimeMessage msg = new MimeMessage(session);
msg.setSentDate(new Date());
InternetAddress fromAddress = new InternetAddress(from);
msg.setFrom(fromAddress);
InternetAddress[] toAddress = new InternetAddress[1];
toAddress[0] = new InternetAddress(email);
msg.setRecipients(Message.RecipientType.TO, toAddress);
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
msg.saveChanges();
transport.sendMessage(msg, msg.getAllRecipients());
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
对于以上代码中的server,from,user,password等这些信息,由于他们是由部署时的实际情况来决定的,所以在实际开发当中,一般不要像以上那样将其固化在代码中.transport用完要关掉,不然会出异常.
transport.close();