Sending email using SMTP and Java

I was on a project a while ago where we needed to be able to send email notifications from the application to the administrator of the database whenever certain errors were trapped. This example shows you how. There are a few libraries that we will need to add in order to get started.

Include the following in your project:

import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;     // Used for date formatting.
After you have added the above libraries you are ready to start to get into the good stuff!

The first step to be able to send email it to create a connection to the SMTP port that is listening. Most of the time the SMTP port for a server is usually 25 but check with your email administrator first to get the right port.

Here is the code to make that initial connection:

private Socket smtpSocket = null;
private DataOutputStream os = null;
private DataInputStream is = null;

Date dDate = new Date();
DateFormat dFormat = _
    DateFormat.getDateInstance(DateFormat.FULL,Locale.US);

try
{ // Open port to server
  smtpSocket = new Socket(m_sHostName, m_iPort);
  os = new DataOutputStream(smtpSocket.getOutputStream());
  is = new DataInputStream(smtpSocket.getInputStream());
            
  if(smtpSocket != null && os != null && is != null)
  { // Connection was made.  Socket is ready for use.
    [ Code to send email will be placed in here. ]
  }
}
catch(Exception e)
{ System.out.println("Host " + m_sHostName + "unknown"); }
Now that you have made the connection it is time to add the code to send off the email. This is pretty straight forward so I will add comments into the code sample itself.
try                        
{   os.writeBytes("HELO\r\n");
    // You will add the email address that the server 
    // you are using know you as.
    os.writeBytes("MAIL From: <you@yourcompany.com>\r\n");
             
    // Who the email is going to.
    os.writeBytes("RCPT To: <theperson@theircompany.com>\r\n");
    //IF you want to send a CC then you will have to add this
    os.writeBytes("RCPT Cc: <theCC@anycompany.com>\r\n");

              
    // Now we are ready to add the message and the 
    // header of the email to be sent out.                
    os.writeBytes("DATA\r\n");
                  
    os.writeBytes("X-Mailer: Via Java\r\n");
    os.writeBytes("DATE: " + dFormat.format(dDate) + "\r\n");
    os.writeBytes("From: Me <me@mycompany.com>\r\n");
    os.writeBytes("To:  YOU <you@yourcompany.com>\r\n");
               
    //Again if you want to send a CC then add this.
    os.writeBytes("Cc: CCDUDE <CCPerson@theircompany.com>\r\n");
                
    //Here you can now add a BCC to the message as well
    os.writeBytes("RCPT Bcc: BCCDude<BCC@invisiblecompany.com>\r\n");
    }
                
    sMessage = "Your subjectline.";

    os.writeBytes("Subject: Your subjectline here\r\n");
    os.writeBytes(sMessage + "\r\n");
    os.writeBytes("\r\n.\r\n");
    os.writeBytes("QUIT\r\n");
                
    // Now send the email off and check the server reply.  
    // Was an OK is reached you are complete.
    String responseline;
    while((responseline = is.readLine())!=null)
    {  // System.out.println(responseline);
        if(responseline.indexOf("Ok") != -1)
            break;
    }
}
catch(Exception e)
{  System.out.println("Cannot send email as an error occurred.");  }
I hope this has helped you out!

You might also like...

Comments

Kevin Saitta Kevin Saitta is an independent Database/Programming consultant specializing in full life cycle development and database design. You can contact Kevin through the Internet at kev@kbaseonline.com.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“We better hurry up and start coding, there are going to be a lot of bugs to fix.”