简体   繁体   中英

javax.mail.MessagingException while sending mail using JavaMail API

I am trying to send as email using JavaMail API, through my gmail account, but I am getting a javax.mail.MessagingException exception

The Code :

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


  }

On debugging, I end up here in Service classs 服务等级

which throws the exception : javax.mail.MessagingException: Host, username, and password must be specified.

Correct these common mistakes . If it still doesn't work, post the debug output .

The only differences that I can find with code that I am using to send to gmail (and which works) is this:

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

and msg.setSentDate(new Date());

you can also add: session.setDebug(true); this might give more clues.

On what line is the exception thrown?

Thanks for the answers. The problem turned out to be a weird one, at least for a newbie like me. Simply put, I had exjello libraries in my classpath. They were messing with my JavaMail API. Once I created a new project and copied my code there, it worked fine. Just to check, I copied the exjello jars to my new project's classpath and it stopped working.

From a layman's point of view, it doesn't seem to be a good idea for a jar file to mess with my execution even though i had not even imported the package to my class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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