繁体   English   中英

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

[英]javax.mail.MessagingException while sending mail using JavaMail API

我试图通过我的gmail帐户使用JavaMail API作为电子邮件发送,但是却收到了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类中 服务等级

引发异常: javax.mail.MessagingException: Host, username, and password must be specified.

纠正这些常见的错误 如果仍然不起作用,请发布调试输出

我可以找到的与发送到gmail(有效)的代码的唯一区别是:

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

和msg.setSentDate(new Date());

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

在哪一行抛出异常?

感谢您的回答。 事实证明,这个问题很奇怪,至少对于像我这样的新手而言。 简而言之,我的类路径中有exjello库。 他们搞砸了我的JavaMail API。 一旦创建了一个新项目并将代码复制到那里,它就可以正常工作。 只是为了检查,我将exjello jars复制到了新项目的类路径中,并停止了工作。

从外行的角度来看,即使我什至没有将包导入到我的类中,jar文件也不会干扰我的执行,这似乎不是一个好主意。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM