1.下载mail.jar和activation.jar包,导入到项目的lib中;
2.配置服务器的邮件类型及其账号和密码:mail.properties
smtpHost=smtp.163.com
from=xxx@163.com
userName=xxxx@163.com
password=*****
3.编写相应的邮件发送类:
public class JavaMail {
private Properties properties;
private Session mailSession;
private MimeMessage mailMessage;
private static Properties props = null;
private static String CONFIGUREFILENAME="/"+"mail.properties";
public JavaMail() {
}
public static void main(String[] args) {
new JavaMail().sendMail(new String[]{"XXXXXXXX@qq.com"},"你好","能收到吗?");
}
public boolean sendMail(String[] accpetMails,String title,String content) {
try {
String smtpHost = this.readValue("smtpHost");
String from = this.readValue("from");;
final String userName = this.readValue("userName");
final String password = this.readValue("password");
if(smtpHost==null || from==null || accpetMails==null ||userName==null || password==null){
return false;
}
properties = new Properties();
//设置邮件服务器
properties.put("mail.smtp.host", smtpHost);
//验证
properties.put("mail.smtp.auth", "true");
//根据属性新建一个邮件会话
mailSession = Session.getInstance(properties,new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
// mailSession.setDebug(true);
//建立消息对象
mailMessage = new MimeMessage(mailSession);
//发件人
mailMessage.setFrom(new InternetAddress(from));
//收件人
InternetAddress[] sendTo = new InternetAddress[accpetMails.length];
for (int i = 0; i < accpetMails.length; i++)
{
sendTo[i] = new InternetAddress(accpetMails[i]);
}
mailMessage.setRecipients(javax.mail.internet.MimeMessage.RecipientType.TO, sendTo);
//主题
mailMessage.setSubject(title);
//内容
mailMessage.setText(content);
//发信时间
mailMessage.setSentDate(new Date());
//存储信息
mailMessage.saveChanges();
//发送
Transport.send(mailMessage);
// trans.close();
return true;
} catch (Exception e) {
// e.printStackTrace();
return false;
} finally {
}
}
// 根据key读取value
public String readValue(String key) {
try {
if(props==null){
props = new Properties();
props.load(this.getClass().getResourceAsStream(CONFIGUREFILENAME));
}
String value = props.getProperty(key);
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
4.执行的过程中,会抛出java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream异常,这是由于javax.mail和javax.activation这两个包已经在javaEE5当中属于基础包了,就是JDK中自带了已经,但是里面的方法与现在外面的mail.jar和activation.jar有一些出入
解决方法是:(源自:http://blog.csdn.net/5iasp/article/details/5935428);
将C:\Users\Administrator\AppData\Local\Genuitec\Common\plugins\com.genuitec.eclipse.j2eedt.core_8.6.0.me201007292038\data\libraryset\EE_5下的javaee.jar下的mail和activation包删除,删除后再次执行;