2013-05-10 50 views
0

我試圖使用JavaMail API,通過我的Gmail帳戶的電子郵件發送,但我得到一個javax.mail.MessagingException的例外javax.mail.MessagingException的同時發送郵件使用JavaMail API

驗證碼:

public static Result sendMail() { 

     Map < String, String[] > values = request().body().asFormUrlEncoded(); 

     String toAddresses = values.get("toaddrs")[0]; 
     String subject = values.get("subject")[0]; 
     String body = values.get("body")[0]; 

     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]", "samplepass"); 
      } 
     }); 

     try { 

      Message message = new MimeMessage(session); 
      message.setFrom(new InternetAddress("[email protected]")); 
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddresses)); 
      message.setSubject(subject); 
      message.setText(body); 

      Transport.send(message); 
      return ok("sent"); 

     } catch (MessagingException e) { 
      return ok("Error in sending email"); 
     } 


    } 

在調試,我在這裏結束了在服務班組長 Service class

會拋出異常:javax.mail.MessagingException: Host, username, and password must be specified.

回答

0

感謝您的回答。問題原來是一個奇怪的問題,至少對於像我這樣的新手來說。簡而言之,我在我的類路徑中有exjello庫。他們搞亂了我的JavaMail API。一旦我創建了一個新項目並在那裏複製我的代碼,它工作正常。爲了檢查,我將exjello jar複製到我的新項目的classpath中,並停止工作。

從外行的角度來看,儘管我還沒有將包導入到我的類中,但似乎並不是一個好的構想,因爲jar文件會混淆我的執行。

0

,我可以說我使用發送到Gmail(和它的作品)代碼中找到的唯一區別是:

Properties props = System.getProperties();// get system props? 
    props.put("mail.smtp.socketFactory.fallback", "false"); 

和 msg.setSentDate(新的Date());

您還可以添加:session.setDebug(true);這可能會提供更多線索。

在什麼行是拋出的異常?

+0

on'Transport.send(message);' – 2013-05-15 07:31:25

1

更正這些common mistakes。如果仍不起作用,請發佈debug output

+0

感謝這個信息,我已經修改了我的代碼,但我想知道;是這些「錯誤」還是最佳實踐,因爲即使我使用與指定內容相反的'Session.getDefaultInstance',我的代碼也能正常工作。其他點相同。 – 2013-05-15 09:06:53

+0

如果你喜歡,你可以稱他們爲「最佳實踐」,但是很多人因爲他們而破壞了程序。幾乎沒有人做過任何這些事情,他們知道**爲什麼他們在做這些事情,他們只是從其他地方剪切和粘貼代碼。 – 2013-05-15 21:36:38

相關問題