1报错信息:
Exception in thread "main" java.lang.NoClassDefFoundError:com/sun/mail/util/LineInputStream
2 需要包mail.jar
3 如果是myeclipse引进的j2ee5包 在安装目录: MyEclipse 6.5/myeclipse/eclipse/plugins/com.genuitec.eclipse.j2eedt.core_6.5.0.zmyeclipse650200806/data/libraryset/EE_5下找到javaee.jar 打开后在j avax文件夹里,删除mail.jar和activation.jar
4 引进自己的mail.jar
总结:这是经过测试的代码如有疑问请联系qq: 263090670
测试源代码:
SendEmail.java
package com.jeecms.cms.action;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail {
protected String to = null;
protected String subject = "Email Test from Beijing China";
protected String body = null;
public SendEmail() {
super();
}
public void setTo(String to) {
this.to = to;
}
public void setBody(String body) {
this.body = body;
}
public void sendmail() {
try
{
String host = "smtp.163.com";
String from = "xxxx@163.com"; //发件箱地址
String to = "xxx@qq.com"; //收件箱地址
String username = "xxxx@163.com"; //发件箱地址
String password = "******"; //发件箱密码
this.body = "This is a test email from 163 use javamail";
MyAuth auth = null;
auth = new MyAuth(username, password);
Properties props = System.getProperties();
props.put("mail.smtp.auth","true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port","25");
Session session = Session.getInstance(props,auth);
session.setDebug(true); //是否调试
//消息对象
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from)); //发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); //收件人
message.setSubject(subject); //主题
//message.setText(body);//内容
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(body);
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
message.setContent(mp);
message.setSentDate(new java.util.Date()); //发件时间
Transport transport = session.getTransport("smtp");
transport.connect(host,username,password); //获得连接
transport.send(message);
}
catch (MessagingException e) {
System.out.println("error" + e.getMessage());
}
}
public static void main(String[] args){
new SendEmail().sendmail();
}
public class MyAuth extends Authenticator{
String userName=null;
String password=null;
public MyAuth(){
}
public MyAuth(String username, String password) {
this.userName = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}
}