Sending an email Programmatically using Java

code in dark text editor

This article will decribe how you can send emails programatically using hte Java programming language. The example below includes a function you can use for easily sending emails from your Java application.


If you have not already, be sure you download and install the latest Java Development Kit (JDK). You can find the download here.

Unforutnatley the javax.mail libraries are not included in the Java JDK, so you will have to download them separately.

The java mail library can be downloaded from the following location:

Once you have downloaded the java mail library, you will need to add the mail.jar file to your Java Build Path. mail.jar is included in the zip file you downloaded from the Oracle page above.

Assuming you are using Eclipse, you can do the following to add the library to your project:

  1. Extract the zip file you downloaded
  2. Open your project in Eclipse
  3. Right click on your project name in the Package Explorer pane
  4. Select Build Path -> Configure Build Path
  5. Select the Libraries Tab
  6. Click Add External JAR’s
  7. Browse to the Mail.Jar you extracted in Step 1
  8. Click Open
  9. Click Ok

Writing Code

Now that we have all of the prerequisites installed, we can start looking at our code. Below is an example application which sends an email using the javax.mail library. This application sends through an SMTP relay that requiers TLS and authentication. Some mail relays do not require either of these things. You will probably want to add some additional code to make that configurable. In this applicaiton, it is hard code to use authentication and TLS.

We have added comments throughout the code to help explain each section.



At this point you have insalled the Java JDK, the Java.mail programming library, and written a small application which can send email messages through an SMTP server that requires authentication and TLS. And you have a function you can call to make it easy to re-use the code.

%d bloggers like this: