1、下载需要的jar文件
http://java.sun.com/products/javamail/ 下载javamail 的压缩包
除非是java6,否则也需要JavaBeans Activation Framework (JAF)
http://java.sun.com/javase/technologies/desktop/javabeans/jaf/index.jsp 下载jaf压缩包
解压压缩包,把javamail压缩包里的mail.jar,smtp.jar和jaf压缩包里的activation.jar三个jar包,拷贝到
%JAVA_HOME%/jre/lib/ext文件夹中。
2、发送邮件类
private String host;//smtp服务器
private String auth;//验证
private String mailAcount;//邮件用户名
private String password;//密码
//共同变量
private MimeMessage mimeMessage;
private Properties props;
private MailAuthenticator mailAuth;
private Session session;
/**
* 构造函数
*/
public Mail(String host,String mailAcount,String password){
this.host=host;
this.auth="true";
this.mailAcount=mailAcount;
this.password=password;
}
/**
* 变量初始化
*/
protected void initialize(){
props = System.getProperties();
// 指定smtp服务器
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", auth);
// 新建一个包含smtp会话的MimeMessage对象
session=Session.getDefaultInstance(props,null);
mimeMessage=new MimeMessage(session);
}
/**
* 设定邮件信息
* @param from,to,subject
* @throws MessagingException
* @throws AddressException
* @throws UnsupportedEncodingException
*/
public void create(String from,String to,String subject) throws AddressException, MessagingException, UnsupportedEncodingException{
//初始化
initialize();
if (from.equals("") || to.equals("") ||subject.equals(""))
{
System.out.println("输入有误");
}else{
//指定送信人
mimeMessage.setFrom(new InternetAddress(from));
//对方邮件地址
mimeMessage.setRecipients(Message.RecipientType.TO, to);
//邮件标题
mimeMessage.setSubject(subject,"GBK");
}
}
/**
* 邮件格式,和内容指定
* @param content
* @throws MessagingException
*/
public void addContent(String content) throws MessagingException{
// 指定邮件格式
mimeMessage.setHeader("Content-Type", "text/html");
// 邮件内容
mimeMessage.setText(content);
}
/**
* 发信
* @throws MessagingException
*/
public void send() throws MessagingException{
// 指定送信日期
mimeMessage.setSentDate(new Date());
// 送信
Transport transport = session.getTransport("smtp");
transport.connect(host,mailAcount,password);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();
}
}
3、收到的邮件类
ReciveMail.java
}
4、接收邮件类
5、发送邮件测试
/**
* @param args
* @throws MessagingException
* @throws AddressException
*/
public static void main(String[] args) {
try {
String from="xxxxxx@xxxxxx.com";
String subject="MailTest";
String content="MailTestMailTestMailTest";
Mail mail=new Mail("smtp.xxxxxx.com","abctest@xxxxxx.com","xxxxxx");
mail.create(from, "xxxxxx@xxxxxx.com",subject);
mail.addContent(content);
mail.send();
System.out.println("Send OK!");
} catch (Exception e) {
e.printStackTrace();
}
}
}