Published on 2019-08-09· Updated on 2021-12-15
The author voluntarily contributed this tutorial as a part of Pepipost Write to Contribute program.
You probably using JavaMail API to compose, write and read emails. The core classes of JavaMail API can be found in the javax.mail and javax.mail.activation packages. While JavaMail API provides a protocol-independent, platform-independent environment for sending and receiving emails but like any other tools, there are few scenarios where the error comes and the developers get stuck.
In this tutorial, we are going to discuss the most commonly occurring JavaMail SMTP errors and a step by step detailed guide on how to solve them.
Before listing possible errors, let's go through one of the most useful JavaMail API property you can use to debug SMTP issues.
Set Properties props = new Properties(); props.put("mail.debug", "true");
Or if you are using javax.mail.Authenticator()
Session.setDebug(true);
Note: At the end of this tutorial, you will find a working code for sending SMTP emails using java mail API and it's corresponding output in debug mode.
You can use the JavaMail API for triggering multiple important events. These events can be a welcome/notification email, forgot password, etc. If you are using JavaMail API for sending SMTP emails, you might end up facing the following errors on your IDE or console.
Exception in thread "main" java.lang.RuntimeException: com.sun.mail.util.MailConnectException: Couldn't connect to host, port:
There can be multiple reasons for this but the most common reason for this error is the port, that you are using to send SMTP mails. Few ISPs/hosting providers block SMTP outgoing port 25. If that the case, try changing the port to 587 or 2525.
Try;
telnet <SMTPHOST> portnumber
If this works, then this means that your port is open.
This error mainly occurs when you try to configure SSL Connection with SMTP host in wrong way.
javax.mail.MessagingException: A1 BAD Invalid SASL argument. t21mb170186760ivm; nested exception is: com.sun.mail.iap.BadCommandException: A1 BAD Invalid SASL argument. t21mb170186760ivm
Previously Java Mail API (up to JavaMail 1.3) didn’t have built-in support for SSL connection, so it was necessary to set socketFactory properties:
Properties props = new Properties(); props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
From the later version of Java Mail API (greater than 1.3).
The easiest way to enable SSL support in current versions of JavaMail is to set the property "mail.smtp.ssl.enable" to "true".
props.put("mail.smtp.ssl.enable", "true");
Once this is enabled, you are ready to use SSL for authentication.
The above error may occur due to wrong imports or handling of javax.mail.authenticator.
There is nothing wrong in using authenticator, but its unnecessarily complex and hard to debug. Instead to avoid error and for saving time use connect method that takes username password when connecting to a Store. And use the static Transport.send method that takes a username and password while sending a message.
Transport.send(msg, user, password);
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: IOException while sending message; nested exception is: java.io.IOException: javax.mail.MessagingException: Empty multipart: multipart/mixed; boundary="----=_Part_0_1480010240.1564228079924"
This error may occur when you are not properly embedding attachment in a standard defined way.
A simple solution to this is to make sure to add MIMEBODYPART class object into the Multipart Class object using addBodyPart(multipart) method
Here is a code snippet:
Multipart multipart = new MimeMultipart(); MimeBodyPart attachmentPart = new MimeBodyPart(); try { attachmentPart.attachFile("H:\7-5-2017statement.pdf"); multipart.addBodyPart(attachmentPart); } catch (IOException e) { e.printStackTrace(); } message.setContent(multipart);
If you send an attachment as above it may happen that your mail is not delivered, due to security constraints maintained at public ESP’s Gmail or Yahoo.
Better First Create File object and then pass to MimeBodyPart.
Find below code snippet:
Multipart multipart = new MimeMultipart(); MimeBodyPart attachmentPart = new MimeBodyPart(); try { File f =new File("H:\7-5-2017statement.pdf"); attachmentPart.attachFile(f); multipart.addBodyPart(attachmentPart); } catch (IOException e) { e.printStackTrace(); } message.setContent(multipart);
You must create a Session object using Session.getInstance instead of Session.getDefaultInstance. Because Session.getDefaultInstance creates a new session with properties that are passed to it for the first time and subsequent calls return the original session that is created the first time and ignores the properties that are passed in subsequent calls.
If there is another code in JVM or app server that creates a session object, you may end up using that object and your properties will be ignored.
To verify whether you are using the correct properties, verify the output properties on the console using;
System.out.println(session.getProperty(username));
To avoid this problem better use;
Session.getInstance
Here is code snippet for sending SMTP mails using java mail API and corresponding output in debug mode.
Maven Dependencies:
<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency> import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class App { public static void main( String[] args ) { // Put recipient’s address String to = "[email protected]"; // Put sender’s address String from = "[email protected]"; final String username = "username";//username generated by Pepipost final String password = "password";//password generated by Pepipost // Paste host address from the SMTP relay tab in Integrations from your Pepipost App String host = "smtp.pepipost.com"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); //props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "587"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); session.setDebug(true); try { // Create a default MimeMessage object. Message message = new MimeMessage(session); // Set From: header field message.setFrom(new InternetAddress(from)); // Set To: header field message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject: header field message.setSubject("My first message with JavaMail"); // Put the content of your message message.setText("Hi there, this is my first message sent with JavaMail"); // Send message System.out.println("Sending msg"); Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException e) { throw new RuntimeException(e); } } }
Sample Output of using in debug mode:
DEBUG: setDebug: JavaMail version 1.4.4 Sending msg DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc] DEBUG SMTP: useEhlo true, useAuth true DEBUG SMTP: useEhlo true, useAuth true DEBUG SMTP: trying to connect to host "smtp.pepipost.com", port 587, isSSL false 220 ESMTP SMTPNY-LB1 Ready DEBUG SMTP: connected to host "smtp.pepipost.com", port: 587 EHLO 192.168.0.10 250-smtpny-lb1.pepipost.com 250-PIPELINING 250-SIZE 50000000 250-VRFY 250-ETRN 250-STARTTLS 250-AUTH PLAIN LOGIN 250-AUTH=PLAIN LOGIN 250-ENHANCEDSTATUSCODES 250-8BITMIME 250 DSN DEBUG SMTP: Found extension "PIPELINING", arg "" DEBUG SMTP: Found extension "SIZE", arg "50000000" DEBUG SMTP: Found extension "VRFY", arg "" DEBUG SMTP: Found extension "ETRN", arg "" DEBUG SMTP: Found extension "STARTTLS", arg "" DEBUG SMTP: Found extension "AUTH", arg "PLAIN LOGIN" DEBUG SMTP: Found extension "AUTH=PLAIN", arg "LOGIN" DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg "" DEBUG SMTP: Found extension "8BITMIME", arg "" DEBUG SMTP: Found extension "DSN", arg "" DEBUG SMTP: Attempt to authenticate DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM AUTH LOGIN 334 VXNlcm5hbWU6 cmlzaGFiaG1pc2hyYTEzMQ== 334 UGFzc3dvcmQ6 U3VtbWVyQDIwMTk= 235 2.7.0 Authentication successful DEBUG SMTP: use8bit false MAIL FROM:<[email protected]> 250 2.1.0 Ok RCPT TO:<[email protected]> 250 2.1.5 Ok DEBUG SMTP: Verified Addresses DEBUG SMTP: [email protected] DATA 354 End data with <CR><LF>.<CR><LF> From: [email protected] To: [email protected] Message-ID: <51228289.1.1564230903309.JavaMail.rishabh@DESKTOP-9HOCLLI> Subject: Tttachment My first message with JavaMail MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Hi there, this is my first message sent with JavaMail . 250 2.0.0 Ok: queued as 042C9D87 QUIT 221 2.0.0 Bye Sent message successfully....
Netcorecloud's toolkit is the solution to all your email problems.
Netcore connects & unifies your data across all sources, connects to your marketing channels and provides you with control over AI Powered automation and personalization.
Rishabh Mishra
Programming Guy! Your coding problem corresponder.