JSP学习笔记(八十六):使用commons-email包发送邮件
commons-email 可以从官方获取,下载地址为:http://commons.apache.org/email/
不仅要添加commons-email-1.1.jar,还需要两个额外的包mail.jar,activation.jar,这两个包可以在j2ee1.4里面找到
commons-email使用SimpleEmail可以发送简单的邮件,使用非常的简单:
public class Test1 {
/**
* 发信人姓名
*/
public static final String MAIL_USERNAME = "your username";
/**
* 发信人密码
*/
public static final String MAIL_PASSWORD = "your password";
/**
* 发信人服务器
*/
public static final String MAIL_HOSTNAME = "smtp.163.com";
/**
* 发信人地址
*/
public static final String MAIL_SENDER = "your username@163.com";
/**
* 发送邮件
* @param reciever 收信人地址
* @param subject 邮件标题
* @param content 邮件内容
* @return 1 发送邮件成功 0 发送邮件失败
*/
public static int sendMail(String reciever, String subject, String content) {
try {
SimpleEmail email = new SimpleEmail();
email.setAuthentication(MAIL_USERNAME, MAIL_PASSWORD);
email.setHostName(MAIL_HOSTNAME);
email.setFrom(MAIL_SENDER);
email.addTo(reciever);
email.setSubject(subject);
email.setContent(content, "text/plain;charset=utf-8");
email.send();
return 1;
} catch (EmailException e) {
return 0;
}
}
public static void main(String[] args) {
System.out.println("start");
Test1.sendMail("a user@gmail.com", "test", "这是一个测试邮件");
System.out.println("finish");
}
/**
* 发信人姓名
*/
public static final String MAIL_USERNAME = "your username";
/**
* 发信人密码
*/
public static final String MAIL_PASSWORD = "your password";
/**
* 发信人服务器
*/
public static final String MAIL_HOSTNAME = "smtp.163.com";
/**
* 发信人地址
*/
public static final String MAIL_SENDER = "your username@163.com";
/**
* 发送邮件
* @param reciever 收信人地址
* @param subject 邮件标题
* @param content 邮件内容
* @return 1 发送邮件成功 0 发送邮件失败
*/
public static int sendMail(String reciever, String subject, String content) {
try {
SimpleEmail email = new SimpleEmail();
email.setAuthentication(MAIL_USERNAME, MAIL_PASSWORD);
email.setHostName(MAIL_HOSTNAME);
email.setFrom(MAIL_SENDER);
email.addTo(reciever);
email.setSubject(subject);
email.setContent(content, "text/plain;charset=utf-8");
email.send();
return 1;
} catch (EmailException e) {
return 0;
}
}
public static void main(String[] args) {
System.out.println("start");
Test1.sendMail("a user@gmail.com", "test", "这是一个测试邮件");
System.out.println("finish");
}
通过调用sendMail方法,就可以发送邮件了。