SendMailUsingJavaFromNetBeans

Tutorial | JavaMail For Starters

Contributed By Agraj Mangal


This tutorial shows you how to send Email using Java.....this means you can write a simple Java Program that sends a mail using your mail account details or you can embed this functionality in your Web Application.

Its been reposted from this blog entry, now a contender for Sun Students Views and Reviews contest.

[[{TableOfContentsTitle=TableOfContents} | {TableOfContents title='Table of Contents'}]]

Pre-requisites


  • It is already shipped with Java SE 6, so Java SE 6 users need not download it separately.
  • Needless to say, NetBeans 6.1 IDE has helped me and other students of my University in completing assignments and projects on time and with ease.
  • So, if you don't have it, download it right away! You can order NetBeans Starter Kit DVD too!


Why so many downloads?


JavaMail consists of various jar files such as mail.jar, mailapi.jar, smtp.jar, pop3.jar whereas JAF mainly consists of activation.jar file. You need to download them and include these jar files in your CLASSPATH so that your JVM(Java Virtual Machine) can find the JAF classes.


Getting Started


  • Open the NetBeans 6.1 IDE.

File:nbstartup_SendMailUsingJavaFromNetBeans.jpg

  • Pretty fast than previous releases. Took about only 14.35 seconds on my machine.


Creating Project


  • Go to File > New Project
  • Under Categories, choose Web and then select to create a simple Web Application.

File:blog1_SendMailUsingJavaFromNetBeans.jpg

  • Click Next and Type in Project Name as JavaMail. Be sure to select Glassfish as your server.

File:blog2_SendMailUsingJavaFromNetBeans.jpg

  • Click Finish and allow NetBeans to create files for your project.


Writing Source Code


  • Now,
    index.jsp
    opens up in the editor by default. Copy and paste the following code in your {index.jsp} file. It simply creates a HTML form that asks for the receiver's email address, subject and message body of the email.
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title> Java Mail </title>
    </head>
    <body>
        <form action="sendMail.jsp" method="POST">
            <table border="0" align="center" cellpadding="5">
                <tbody>
                    <thead><tr> <td colspan="3" align="center">
                    <b> Send Mail </b> </td> </tr> </thead>
                    <tr>
                        <td> To </td> <td> : </td>
                        <td> <input type="text" name="to" value="" /> </td>
                    </tr>
                    <tr>
                        <td> Subject </td> <td> : </td>
                        <td> <input type="text" name="subject" value="" /> </td>
                    </tr>
                    <tr>
                        <td> Message </td> <td> : </td>
                        <td> <textarea name="message" rows="8" cols="30">
                        </textarea></td>
                    </tr>
                    <tr>
                        <td colspan="3" align="center">
                        <input type="submit" value="Send Mail" />
                              
                        <input type="reset" value="Reset" />
                        <td>
                    </tr>
                </tbody>
            </table>
        </form>
    </body>
</html>
  • Save it and it looks like-

File:blog3_SendMailUsingJavaFromNetBeans.jpg

  • Now, we create a bean in which we store all the mail related information : sender's email id and password and receiver's email id, subject and message body of the email and the name of the smtp server that we use to send email.

Using Wizard

  • Right-click the project node and select New > Java Class
  • A wizard like the following appears, fill in the Class Name as Mail and Package Name as jMail

File:blog4_SendMailUsingJavaFromNetBeans.jpg

  • Mail.java
    class open up in the editor.
  • Add the following
    instance variables
    to the bean-
String to;
String from;
String message;
String subject;
String smtpServ;
  • Generate the getter, setter methods for them by right-clicking in the editor and select Refactor > Encapsulate Fields. Then check all the setter and getter methods and click Refactor so that the IDE generates code for them.

File:blog-refactor_SendMailUsingJavaFromNetBeans.jpg

Using JavaMail API

  • Now, we make use of the JavaMail API and send mail using the following code. But before doing that, import the required packages.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
  • Now, as you has already noticed, NetBeans is showing errors showing that it doesn't know of javax.mail package even if you have correctly downloaded and installed the JAF and JavaMail API. To make NetBeans aware of the existence of these packages, perform the following steps:
  • Right click the project node (JavaMail), click Properties to change properties of the project.
  • Now go to Libraries Tab (since we need to add jar files to our project).

File:blog5_SendMailUsingJavaFromNetBeans.jpg

  • Click on Add JAR/Folder Button. A window opens up.
  • Browse to the location where you have installed/unzipped your JavaMail API and then include following jar's;
  • activation.jar
  • pop3.jar
  • mail.jar
  • mailapi.jar
  • smtp.jar
  • If you do not perform this step, then NetBeans will not recognize JAF and JavaMail classes and hence will not compile the program given below which makes use of classes such as Message, Session, Transport etc.
  • Compile your program to check whether you have been able to successfully include these jar files or not.

Implementing sendMail()

  • Now, the main function
    sendMail( )
    , which is actually responsible for sending mail:
public int sendMail(){
        try
        {
            Properties props = System.getProperties();
              // -- Attaching to default Session, or we could start a new one --
              props.put("mail.transport.protocol", "smtp" );
              props.put("mail.smtp.starttls.enable","true" );
              props.put("mail.smtp.host",smtpServ);
              props.put("mail.smtp.auth", "true" );
              Authenticator auth = new SMTPAuthenticator();
              Session session = Session.getInstance(props, auth);
              // -- Create a new message --
              Message msg = new MimeMessage(session);
              // -- Set the FROM and TO fields --
              msg.setFrom(new InternetAddress(from));
              msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
              msg.setSubject(subject);
              msg.setText(message);
              // -- Set some other header information --
              msg.setHeader("MyMail", "Mr. XYZ" );
              msg.setSentDate(new Date());
              // -- Send the message --
              Transport.send(msg);
              System.out.println("Message sent to"+to+" OK." );
              return 0;
        }
        catch (Exception ex)
        {
          ex.printStackTrace();
          System.out.println("Exception "+ex);
          return -1;
        }
  }

// Also include an inner class that is used for authentication purposes

private class SMTPAuthenticator extends javax.mail.Authenticator {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username =  "Java.Mail.CA@gmail.com";           // specify your email id here (sender's email id)
            String password = "javamail";                                      // specify your password here
            return new PasswordAuthentication(username, password);
        }
  }
  • Save the file and compile it.
  • Now add another JSP, name it sendMail.jsp
  • Add the following code to it that instantiates
    JavaBean Object
    and set properties of {JavaBean} using the parameters passed to it using index.jsp
<jsp:useBean id="mail" scope="session" class="jMail.Mail" />
<jsp:setProperty name="mail" property="to" param="to" />
<jsp:setProperty name="mail" property="from" value="Java.Mail.CA@gmail.com" />
<jsp:setProperty name="mail" property="smtpServ" value="smtp.gmail.com" />
<jsp:setProperty name="mail" property="subject" param="subject" />
<jsp:setProperty name="mail" property="message" param="message" />
  • The main point to note here is the value of
    smtpServ
    that we have passed. Here, we are using a gmail id, so its smtp server name should be used, which is "smtp.gmail.com".
  • If you want to use your own email id, then you have to make few changes as specified above and also change the value of
    smtpServ
    property to your smtp server name.

Invoking sendMail()

  • Add the following code to sendMail.jsp that calls the
    sendMail()
    method of the bean. Yes, a bean can have other methods except getter and setter methods. Its perfectly legal. :-)
 <%
String to = mail.getTo();
int result;
result = mail.sendMail();
if(result == 0){
    out.println(" Mail Successfully Sent to "+to);
}
else{
    out.println(" Mail NOT Sent to "+to);
}  
%>
  
  • Save your project and Run it to see that it actually works
  • The whole project is available here for download.

Notes


  • There is much to JavaMail than what is mentioned here. For more read on JavaMail & Glassfish
  • Read the following links to understand what's actually happening in the code given above JavaMail Quick Start jGuru : Fundamentals of JavaMail API
  • Related & Advanced- Creating JavaMail Client On NB
  • Please do not modify the password for the account Java.Mail.CA@gmail.com
  • I created it only for demo purposes and have given out the account details as on all tutorials/demos about JavaMail that i have seen online leave these fields empty and also leave smtp server name fields empty, which only adds to confusion for novices.
  • Any comments, suggestions and corrections are welcome.

Version Compatability


Works with NetBeans 6.1 as said above. Try this out on your version, and make sure to notify us if anything goes wrong!

Thank you!

Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo