2014-11-08 147 views
1

我试图从我的struts应用程序发送测试邮件。我有一个简单的jsp页面和相应的页面动作,我下载了一个简单的代码发送一封邮件,代码如下。通过带有java邮件API的struts发送电子邮件

package java4s; 

import java.util.Properties; 

import javax.mail.Message; 
import javax.mail.MessagingException; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeMessage; 
public class mailtest { 

    public static void main(String[] args) { 
     Properties props = new Properties(); 
     props.put("mail.smtp.host", "smtp.gmail.com"); 
     props.put("mail.smtp.socketFactory.port", "465"); 
     props.put("mail.smtp.socketFactory.class", 
       "javax.net.ssl.SSLSocketFactory"); 
     props.put("mail.smtp.auth", "true"); 
     props.put("mail.smtp.port", "465"); 

     Session session = Session.getDefaultInstance(props, 
      new javax.mail.Authenticator() { 
       protected PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication("[email protected]","********"); 
       } 
      }); 

     try { 

      Message message = new MimeMessage(session); 
      message.setFrom(new InternetAddress("[email protected]")); 
      message.setRecipients(Message.RecipientType.TO, 
        InternetAddress.parse("[email protected]")); 
      message.setSubject("Testing Subject"); 
      message.setText("Dear Mail Crawler," + 
        "\n\n No spam to my email, please!"); 

      Transport.send(message); 

      System.out.println("Done"); 

     } catch (MessagingException e) { 
      throw new RuntimeException(e); 
     } 
    } 

    } 

此代码也在发送邮件。我已经将它更改为一个类,以便我可以创建一个对象并从我的操作中调用该函数。像如下

public class mailtest 
{ 

void mailSend() 
{ 

//Same code as above 
} 

} 

但是,当我在我的操作页面创建该类的对象是给我一个例外如下..

根源

java.lang.NoClassDefFoundError: javax/mail/MessagingException 
    java4s.mailsender.execute(mailsender.java:50) //on this line i've created object of the  mailtest class 
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
    java.lang.reflect.Method.invoke(Unknown Source) 

希望你能理解,请如果您需要更多的说明意见。

回答

1

首先,修复所有这些common mistakes

我猜你没有在Java EE应用程序服务器上运行; Java EE应用程序服务器包括JavaMail作为标准部分。

如果您刚刚在Tomcat中运行,则需要通过将JavaMail jar文件放入WAR文件的WEB-INF/lib目录中或将其放入Tomcat's lib directory

+0

我已将mail.jar添加到我的课程目录中。现在它的工作。谢谢。 – 2014-11-09 15:16:18

相关问题