2013-05-28 148 views
0

我正在用Apache Commons電子郵件API嘗試下列代碼,並且它在上下文中引發錯誤。任何幫助?javax.naming.NoInitialContextException Apache Commons api

import java.util.Properties; 

import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 

import org.apache.commons.mail.EmailException; 
import org.apache.commons.mail.SimpleEmail; 


public class email { 

    /** 
    * @param args 
    * @throws EmailException 
    */ 
    public static void main(String[] args) throws EmailException { 
     // TODO Auto-generated method stub 
     Properties props = new Properties(); 
     props.put("mail.smtp.auth", "true"); 
     props.put("mail.smtp.starttls.enable", "true"); 
     props.put("mail.smtp.host", "smtp.gmail.com"); 
     props.put("mail.smtp.port", "587"); 
     Session session = Session.getInstance(props, 
        new javax.mail.Authenticator() { 
        protected PasswordAuthentication getPasswordAuthentication() { 
         return new PasswordAuthentication("[email protected]", "password"); 
        } 
        }); 
SimpleEmail se = new SimpleEmail(); 
se.addTo("[email protected]"); 
se.setFrom("[email protected]"); 
se.setSubject("Test email"); 
se.setMsg("Hi there"); 
se.send(); 

    } 

} 

它引發以下錯誤。我應該在哪裏設置什麼來克服這個問題?在這方面的任何幫助?

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial 
    at javax.naming.spi.NamingManager.getInitialContext(Unknown Source) 
    at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source) 
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source) 
    at javax.naming.InitialContext.lookup(Unknown Source) 
    at javax.xml.registry.samples.SimpleClient.doit(Unknown Source) 
    at javax.xml.registry.samples.SimpleClient.main(Unknown Source) 

+0

請問你'doit'方法是什麼樣子? 'javax.xml.registry.samples.SimpleClient'和你發佈的代碼是一樣的嗎? – longhua

+0

我擁有的就是這個代碼嗎? AM我錯過了什麼?什麼是doit方法?你能幫我嗎? – user1411601

+0

我想你正在使用錯誤的類?你如何運行你的Java類?你應該使用'email'類,而不是'javax.xml.registry.samples.SimpleClient'。請檢查您的堆棧跟蹤。 – longhua

回答

1

你混合javax.mailApache的通用電子郵件。此代碼應爲你工作:

public static void main(String[] args) { 
{ 
    try 
    { 
     Email se = new SimpleEmail(); 

     se.setHostName("smtp.googlemail.com"); 
     se.setSmtpPort(465); 
     se.setAuthenticator(new DefaultAuthenticator("[email protected]", "password")); 
     se.setSSLOnConnect(true); 


     se.addTo("[email protected]"); 
     se.setFrom("[email protected]"); 
     se.setSubject("Test email"); 
     se.setMsg("Hi there"); 
     se.send(); 
    } 
    catch(EmailException e) { 
     System.out.println("Uh oh! It doesn't work!"); 
    } 
} 

更多信息:

Apache Commons Email Userguide

+0

完美,謝謝!它的作品! – user1411601

+0

@ user1411601不客氣,您應該將其標記爲已接受社區! –

+0

完成,再次感謝! – user1411601

相關問題