First time working with java mail. I’m following this tutorial but I already fail at sending a basic message and I get a very strange error:
java.util.ServiceConfigurationError: javax.mail.Provider: Provider com.sun.mail.imap.IMAPProvider not a subtype
Strange because I’m not using IMAP anywhere in my code:
Properties mailProps = new Properties(); mailProps.put("mail.transport.protocol", "smtp"); mailProps.put("mail.host", "smtp.mydomain.com"); mailProps.put("mail.from", "me@mydomain.com"); mailProps.put("mail.smtp.port", "25"); Session session = Session.getDefaultInstance(mailProps); SMTPMessage m = new SMTPMessage(session); MimeMultipart content = new MimeMultipart(); MimeBodyPart mainPart = new MimeBodyPart(); mainPart.setText("test"); content.addBodyPart(mainPart); m.setContent(content); m.setSubject("Demo message"); m.setRecipient(RecipientType.TO, new InternetAddress("john@example.com")); Transport.send(m);
The error happens on last line (send). I know the smtp server is correct and working.
Any advice why this happens and how I can solve it?
EDIT: obviously the addresses/hosts are changed here and I’m using real ones that work in the actual code.
Advertisement
Answer
it turns out I was running into multiple issues:
- Issue with tutorial
It uses com.sun.mail.smtp.SMTPMessage
but in my case that doesn’t work but using javax.mail.internet.MimeMessage
works fine.
- Root cause of error
Above code runs within a 3rd party eclipse based application and they seem to interfere with each other. The solution for this can be found here:
Thread t = Thread.currentThread(); ClassLoader ccl = t.getContextClassLoader(); t.setContextClassLoader(session.getClass().getClassLoader()); try { Transport.send(m); } finally { t.setContextClassLoader(ccl); }
Adjusting the code accordingly make it work.