[SOLVED] Most common JavaMail API SMTP Errors

Published on 2019-08-09· Updated on 2023-10-26

The author voluntarily contributed this tutorial as a part of Pepipost Write to Contribute program.

Introduction

JavaMail API is widely used for composing, sending, and receiving emails in Java applications. The core classes of the JavaMail API can be found in the javax.mail and javax.mail.activation packages. However, as with any tool or library, developers may encounter various issues and errors during its use.

In this tutorial, we aim to address the most common JavaMail SMTP errors and provide step-by-step guidance on how to resolve them. This approach can be highly beneficial to developers who use the JavaMail API, as it helps troubleshoot issues and improve the robustness of their email-related functionalities. 

Before listing possible errors, let's go through one of the most useful JavaMail API properties 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 JavaMail API and its corresponding output in debug mode.

List Of Common JavaMail SMTP Errors


Using the JavaMail API for triggering important events like welcome or notification emails, password reset emails, and other types of emails is a common and practical use case. However, it's important to be prepared for potential errors that may arise during the development process. These errors can impact the successful delivery of your emails and the functionality of your application. Troubleshooting and resolving these errors is essential for ensuring a smooth email communication system in your Java application.

Error 1: Could not connect to SMTP host: com.sun.mail.util.MailConnectException: Couldn't connect to host🔗

Exception in thread "main" java.lang.RuntimeException: com.sun.mail.util.MailConnectException: Couldn't connect to host, port:

One of the most common reasons for SMTP email sending errors is the port used for SMTP communication. Many ISPs and hosting providers block outgoing traffic on port 25 as a measure to prevent spam or abuse. If you encounter such restrictions, a practical solution is to switch to alternative SMTP ports such as 587, 2525, or 465 (which is often used for SSL/TLS-secured connections). Making this port adjustment can help ensure that your SMTP emails can be sent successfully despite these restrictions.

Try;

 telnet <SMTPHOST> portnumber

If this works, then this means that your port is open.

Error 2: A1 BAD Invalid SASL argument🔗

This error mainly occurs when you try to configure an SSL connection with an SMTP host in the 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) did not have built-in support for SSL connection and 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.

Error 3: Using Authenticator just to supply username and password 🔗

This can occur due to incorrect imports or issues in handling javax.mail.authenticator. While using an authenticator can be a valid approach, it might introduce complexity and make debugging more challenging. To simplify and avoid potential errors, you can opt for alternative methods:

When connecting to a Store (e.g., for receiving emails), you can use the connect method that takes the username and password as parameters. This approach simplifies the authentication process and helps save time.

When sending an email, you can use the static Transport.send method, which also accepts a username and password as parameters. This method makes it more straightforward to include authentication details when sending messages.

Transport.send(msg, user, password);

Using these methods can streamline the authentication process and reduce the chances of errors, making your JavaMail-based email functionality more reliable and easier to manage. 

 

Error 4: You may get Empty multipart Error While Sending Attachment 🔗

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 embedding attachment in a 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);

Sending an attachment as described above may result in your email not being delivered, owing to the security constraints upheld by popular ESPs such as Gmail or Yahoo. It's advisable to first create a File object and then pass it to a MimeBodyPart for better compatibility and to ensure successful email delivery.

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

Error 5: It may happen that you're not using the configuration you think you're using. 🔗

To ensure the correct configuration, create a session object using Session.getInstance instead of Session.getDefaultInstance. Session.getDefaultInstance creates a new session with the properties provided during the first call, and subsequent calls will return the original session created during the first call, disregarding any properties passed in those subsequent calls.

If there is any other code within the JVM or app server that also creates a session object, you might unintentionally use that existing session, causing your specified properties to 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 a code snippet for sending SMTP mails using java mail API and corresponding output in debug mode.

Maven Dependencies:

  • Add this in pom.xml
<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....
 

Grade My Email
Check your spam now?

Netcorecloud's toolkit is the solution to all your email problems.

Rishabh Mishra

Programming Guy! Your coding problem corresponder.

You can also explore

Netcore connects & unifies your data across all sources, connects to your marketing channels and provides you with control over AI Powered automation and personalization.

Deploy emails that are
screenshot worthy!

Stop settling for static emails - use Netcore's platform to create dynamic, interactive emails that convert.
Let's Deploy
Get Started Now