Library code snippets

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!

Comments

  1. 21 Feb 2007 at 11:47
    well.. i think
  2. 20 Jan 2007 at 18:48
    i think that JavaMAIL API is better than the above listed simple socekt programming
  3. 27 Nov 2006 at 15:30
    while this code works well for short emails, it may experience problems when sending emails that exceed the 72 character per-line limit as defined by the RFC.

    Here are a few related tutorials on sending/retrieving emails with Java.

    http://www.jscape.com/articles/sending_email_smtp_ssl_gmail.html

    http://www.jscape.com/articles/retrieving_email_using_java.html

    http://www.jscape.com/articles/sending_email_attachments_using_java.html









  4. 10 Nov 2006 at 07:35

    Dear kavitha madam,

    Iam designing a site ... iam using "Email Component" in that...

    I have seen ur code..I think it is for "Intranet" only..

    how can i develop a site with "Email to any Yahoomail , gmail, hotmail..etc"..

    I think u will understandmy problem....

    Iam designing in JSP, servlets..

    Plz help me ..urgently..

    Thanking u mam........and members

     

                     regards ,

              roddiack

  5. 23 Nov 2005 at 07:43

    Hey guys I am 5th year Electrical Enginnering Student Jimma University Ethiopia
    I have planed  for final year project  Machine Controll using voice command through Telephone
    now I face difficulty only on speech-to-text source code on VB so please anyone who is worked on
    speech-to-text please send me source code.
    And I kindly aske that anyone who have knowledge on this field and he/she wants to advise me
    Please contact me


    Thank You Very Much


    my e-mail is   desuka4@gmail.com

  6. 08 May 2003 at 03:16

    Quote:
    [1]Posted by nextwave on 27 Feb 2003 09:09 PM[/1]
    how do you do the opposite (receive email).....
    can you use a ServerSocket to listen and a Socket for connections????
    if so what kinds of input stream do you use to read from the Socket????


    any help or resources would be greatley appreciated.

  7. 27 Feb 2003 at 21:09

    how do you do the opposite (receive email).....
    can you use a ServerSocket to listen and a Socket for connections????
    if so what kinds of input stream do you use to read from the Socket????


    any help or resources would be greatley appreciated.

  8. 09 Oct 2002 at 06:35


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


    I have got problems with this statement..... can anyone help me see if there is any problem??? the error msg is something like this when i compil e it.........
    --->


    Email.java:13: ';' expected.
       DateFormat dFormat = _  
                             ^
    1 error
    Finished



  9. 07 Oct 2002 at 14:23

    what is the need of this code !!!!
    cause when i use this i normally get time out.
    pls clarify thank
       
       while((responseline = in.readLine())!=null)
                           {  
                               if(responseline.indexOf("OK") != -1)
                               {l_send = "NO";
                                break;}
                            }

  10. 01 Jan 1999 at 00:00

    This thread is for discussions of Sending email using SMTP and Java.

Leave a comment

Sign in or Join us (it's free).

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.
AddThis

Related podcasts

  • Java Posse #224 - Holiday 2008 Special

    Holiday 2008 Special Fully formatted shownotes can always be found at http://javaposse.comOur traditional Odyssey into non-Java geeking, although there is a fair amount of Java meat if you can make it through to the latter half of the podcast. It's long, it's rambling, it's off topic, and it...

Events coming up

  • Nov 17

    Portland Java User Group

    Portland, United States

    This month's topic: TBD----------PJUG meetings start with eat+meet+greet time (pizza and beverages are provided), followed by the featured speaker, then some time for Q&A, discussion, and sometimes a drawing to give away swag. :)It is...

Want to stay in touch with what's going on? Follow us on twitter!