Connect to SMTP Server using Java

Connect to SMTP Server using Java

The SMTP is a commonly used email protocol to send emails from the client applications to the email servers. Before communicating with an SMTP server, you need to establish a connection. In this article, you will learn how to connect to an SMTP server programmatically using Java. Furthermore, the article will cover how to connect to the SMTP servers via SOCKS or HTTP proxies.

Java API to Connect to SMTP Server

In order to connect to an SMTP server, we will use Aspose.Email for Java. It is a powerful API that lets you create feature-rich email client applications using Java. Furthermore, it provides simplified ways to connect to the SMTP servers. You can either download the API’s JAR or install it using the following Maven configurations.

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java API</name>
    <url>http://repository.aspose.com/repo/</url>
</repository>
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-email</artifactId>
    <version>21.3</version>
    <classifier>jdk16</classifier>
</dependency>

Connect to an SMTP Server using Java

The following are the steps to connect to an SMTP server.

  • Create an object of SmtpClient class and initialize it with the host’s address.
  • Set username, password, port, and security options using the SmtpClient object.
  • Send the email.

The following code sample shows how to connect to an SMTP server using Java.

Use Proxy to Connect to an SMTP Server

In various cases, the SMTP servers are secured using the proxy. Therefore, you have to connect to the SMTP server via the proxy server. For such cases, Aspose.Email for Java provides the following methods.

Connect to SMTP Servers via SOCKS Proxy in Java

Aspose.Email for Java provides the support for versions 4, 4a and 5 of SOCKS proxy protocol. The following are the steps to connect to an SMTP server via SOCKS proxy.

  • Create an object of SmtpClient class and initialize it with the host, username, and password.
  • Create an object of the SocksProxy class and set the server’s address, port, and SOCKS version.
  • Set proxy using SmtpClient.setProxy(SocksProxy) method.
  • Send emails.

The following code sample shows how to connect to an SMTP server via SOCKS proxy.

Connect to an SMTP Servers via HTTP Proxy in Java

The following are the steps to connect to an SMTP server via HTTP proxy.

The following code sample shows how to connect to an SMTP server via HTTP proxy.

Get a Free API License

You can get a free temporary license in order to use Aspose.Email for Java without evaluation limitations.

Conclusion

In this article, you have learned how to connect to an SMTP server programmatically using Java. In addition, you have seen how to use SOCKS and HTTP proxies to connect to an SMTP server. You can explore more about Aspose.Email for Java using documentation. Furthermore, you can submit your queries via our forum.

See Also