2013-05-10 54 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

相关问题