public class MailClient
{
public void sendMail(String mailServer, String from, String to,
String subject, String messageBody)
throws MessagingException, AddressException
{
// Setup mail server
Properties props = System.getProperties();
props.put("mail.smtp.host", mailServer);
// Get a mail session
Session session = Session.getDefaultInstance(props, null);
// Define a new mail message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
// Create a message part to represent the body text
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(messageBody);
// use a MimeMultipart as we need to handle the file attachments
Multipart multipart = new MimeMultipart();
// add the message body to the mime message
multipart.addBodyPart(messageBodyPart);
// Put all message parts in the message
message.setContent(multipart);
// Send the message
Transport.send(message);
}
public static void main(String[] args)
{
try
{
MailClient client = new MailClient();
String server="mail.gmail.com";
String from="johndoe@gmail.com";
String to = "johndoe@gmail.com";
String subject="Test";
String message="Testing";
client.sendMail(server,from,to,subject,message);
}
catch(Exception e)
{
e.printStackTrace(System.out);
}
}
}
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
at javax.mail.Session.loadProvidersFromStream(Session.java:928)
at javax.mail.Session.access$000(Session.java:174)
at javax.mail.Session$1.load(Session.java:870)
at javax.mail.Session.loadResource(Session.java:1084)
at javax.mail.Session.loadProviders(Session.java:889)
at javax.mail.Session.<init>(Session.java:210)
at javax.mail.Session.getDefaultInstance(Session.java:299)
at javax.mail.Session.getDefaultInstance(Session.java:339)
at com.happy.mail.SendMail.send(SendMail.java:58)
at com.happy.mail.SendMail.main(SendMail.java:37)
[color=red]解决方案[/color]
[size=medium]今天写代码还能纳闷的遇到了一个问题,就是这个异常:Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream,我向佛祖发誓这个包我绝对导入了,但是异常告诉我找不到这个包!,以前写过java发送邮件的代码,没见过这样的异常,今天就遇上了,或许是因为我用了不同的方法造成的,对网上资源一顿搜索,最后发现是和Java EE 5 Libraries/javaee.jar/mail冲突,找到病原那就立刻诊治:
用解压文件打开C:\Program Files\Genuitec\Common\plugins\com.genuitec.eclipse.j2eedt.core_8.5.0.me201003231033\data\libraryset\EE_5\javaee.jar,删除其中的mail就好了,我这个是以myeclipse8.5为例子的,因为我用的是8.5,但是方法都一样,
注意:打开javaee.jar包时用好压软件是打不开的,要用WinRAR软件!希望碰到这样问题的朋友都可以解决!
[/size]
"D:\Java\Genuitec\Common\plugins\com.genuitec.eclipse.j2eedt.core_8.6.0.me201007292038\data\libraryset\EE_5\javaee.jar"
// 打开上面的文件夹,然后删除里面的mail文件夹,OK!