2011-03-08 40 views
3

我想發送一封電子郵件尤斯的EJB,但我唯一的事情,我得到的回報在此異常:從Java無狀態EJB發送電子郵件(符合Java EE 6)

java.lang.RuntimeException: javax.mail.AuthenticationFailedException: failed to connect, no password specified? 

這是怎麼了我的EJB看起來像:

@Stateless(name = "ejbs/EmailServiceEJB") 
public class EmailServiceEJB extends Authenticator implements IEmailServiceEJB { 

public PasswordAuthentication getPasswordAuthentication() { 
    return new PasswordAuthentication("[email protected]", 
      "xxxxxxx"); 
} 

public void sendAccountActivationLinkToBuyer(String destinationEmail, 
     String name) { 
    // OUR EMAIL SETTINGS 
    String host = "smtp.gmail.com";// Gmail 
    int port = 465; 
    String serviceUsername = "[email protected]"; 
    String servicePassword = "xxxxxxx";// Our Gmail password 

    Properties props = new Properties(); 
    props.put("mail.smtp.user", serviceUsername); 
    props.put("mail.smtp.host", host); 
    props.put("mail.smtp.port", port); 
    props.put("mail.smtp.starttls.enable", "true"); 
    props.put("mail.smtp.debug", "true"); 
    props.put("mail.smtp.auth", "true"); 
    props.put("mail.smtp.socketFactory.port", port); 
    props.put("mail.smtp.socketFactory.class", 
      "javax.net.ssl.SSLSocketFactory"); 
    props.put("mail.smtp.socketFactory.fallback", "false"); 

    // Destination of the email 
    String to = destinationEmail; 
    String from = "[email protected]"; 

    // Creating a javax.Session with the our properties 
    Session session = Session.getInstance(props); 

    try { 
     Message message = new MimeMessage(session); 
     // From: is our service 
     message.setFrom(new InternetAddress(from)); 
     // To: destination given 
     message.setRecipients(Message.RecipientType.TO, 
       InternetAddress.parse(to)); 
     message.setSubject("Comfirm your account"); 
     // Instead of simple text, a .html template should be added here! 
     message.setText("Welcome....... "); 

     Transport transport = session.getTransport("smtp"); 
     transport.connect(host, port, serviceUsername, servicePassword); 
     Transport.send(message, message.getAllRecipients()); 
     transport.close(); 

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

} 

}

我不知道爲什麼它口口聲聲說沒有指定密碼是什麼嗎? SSLSocketFactory與它有關係嗎?我需要在某處調用getPasswordAuthenticion()方法,或者從我的託管bean調用第二個方法是我需要的嗎?

+0

您是否在使用像GlassFish這樣的應用程序服務器? – musiKk

+0

是Glassfish 3.0 – sfrj

回答

8

我不知道爲什麼你的代碼不能正常工作,但你可能想看看這個:

http://spitballer.blogspot.com/2010/02/sending-email-via-glassfish-v3.html

它顯示了在Java EE中,配置電子郵件的另一種方法,我認爲效果更好。連接詳細信息在容器級配置,就像容器管理的數據庫連接一樣。

+1

借調。當我詢問應用服務器時,這就是我想到的。這絕對是要走的路。 – musiKk

+0

這是一個很好的答案:)我只用了10分鐘,現在我的應用程序正在發送電子郵件使用gmail帳戶,哇,我很驚訝這是多麼容易:)我愛玻璃魚嘿嘿...謝謝你們。 – sfrj

1

閱讀SPF和DKIM。

很難知道這裏出了什麼問題,因爲您的代碼只是所需信息的一半。真正的問題可能是您的代碼不適合您的環境,而SPF和DKIM通常是連接到任何公共SMTP服務器併發送電子郵件不起作用的原因。

至少在閱讀了關於SPF和DKIM的一些信息之後,您可以知道這是您的案例中的問題,還是您的案例中不存在問題。