使用JavaMail API发送邮件时出现javax.mail.MessagingException

时间:2013-05-10 13:16:16

标签: java playframework-2.0 javamail

我正在尝试使用JavaMail API通过我的Gmail帐户发送电子邮件,但我收到了javax.mail.MessagingException异常

守则:

  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("samplemail@gmail.com", "samplepass");
          }
      });

      try {

          Message message = new MimeMessage(session);
          message.setFrom(new InternetAddress("samplemail@gmail.com"));
          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类中 Service class

抛出异常:javax.mail.MessagingException: Host, username, and password must be specified.

3 个答案:

答案 0 :(得分:1)

纠正这些common mistakes。如果仍然无效,请发布debug output

答案 1 :(得分:0)

我用代码发现的唯一区别是我用来发送到gmail(以及哪些有效):

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

和         msg.setSentDate(new Date());

你也可以添加:session.setDebug(true);这可能会提供更多线索。

抛出的异常在哪一行?

答案 2 :(得分:0)

感谢您的回答。问题结果是一个奇怪的问题,至少对于像我这样的新手来说。简单地说,我的classpath中有exjello库。他们搞乱了我的JavaMail API。一旦我创建了一个新项目并在那里复制了我的代码,它就可以了。为了检查,我将exjello罐子复制到我的新项目的类路径中,它停止了工作。

从外行人的角度来看,即使我甚至没有将包导入我的班级,但是jar文件似乎不是一个好主意,因为我甚至没有将包导入到我的班级。