Home Struts Hibernate-spring Send Mail Bean
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Send Mail Bean

Advertisement
In our application we have developed mailer bean that sends welcome email when a new user is registered to the system.

Send Mail Bean

   

In our application we have developed mailer bean that sends welcome email when a new user is registered to the system. Mail Bean also used when user asks for the forgotten password.

 

In this article we use Java Mail API to send emails. This is standard part of  J2EE.You can  download this API from http://java.sun.com/products/javamail/.If you download this API ,you will get mail.jar file .Put this file in your tomcat's lib directory.

 

Now we write java source code to send a mail. Very first we imports some java packages which allow you to use methods. 

package roseindia.web.common;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendMail
{

  private String strSmtp;

    
    public void setStrSmtp(String strSmtp){
    this.strSmtp=strSmtp;
    }

  public String getStrSmtp(){
    return this.strSmtp;
  }

  

  public void sendMail( String recipients[ ], String subject, String message ,
 String from)
 throws MessagingException
  {
    boolean debug = false;

     //Set the host smtp address

     Properties props = new Properties();
     props.put("mail.smtp.host", getStrSmtp());

     

    // create some properties and get the default Session

    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);


    // create a message
    Message msg = new MimeMessage(session);


    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length]; 
    for (int i = 0; i < recipients.length; i++)
    {
      addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);
     


    // Optional : You can also set your custom headers  in the Email if you Want
    //msg.addHeader("MyHeaderName", "myHeaderValue");

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");

    //send message
    Transport.send(msg);
  }
}


After that we declare a member variable  'strSmtp' to store name of the mail server for the connection. This strSmtp represents the host name or IP address of mail server. Here we use setter and getter methods to set or get the value of strSmtp. After getting the value of  strSmtp  we need to set  this value  into a property object.

   Properties props = new Properties();
   props.put("mail.smtp.host", getStrSmtp());

The  property 'mail.smtp.host' contains the information about mail server  to be used for the connection. Now this is time to connect with mail server and create a session. This is done by a specific class of Java Mail API named Session. We use the following code for this purpose-

   Session session = Session.getDefaultInstance(props, null);
   session.setDebug(debug); 

After you have the Session, you can create a Message from the Session. This  Message class represents the email message. Message class is an abstract class, so you must create an instance of a subclass. That subclass is Mime Message.

   Message msg = new MimeMessage(session);

After we have the Message, we will create a instances of InternetAddress class for from and to email addresses. 

   InternetAddress addressFrom = new InternetAddress(from);

   InternetAddress[] addressTo = new InternetAddress[recipients.length]; 
   for (int i = 0; i < recipients.length; i++)
   {
    addressTo[i] = new InternetAddress(recipients[i]);
   }

Now, by using setFrom() and setRecipients() methods of Message class we will set from and recipients email addresses 

   msg.setFrom(addressFrom);
   msg.setRecipients(Message.RecipientType.TO, addressTo);

Now, we will set subject of message and content type.  

    // Setting the Subject and Content Type
    
msg.setSubject(subject);
   msg.setContent(message, "text/plain");

Finally our message is set, send it with the Transport class

  Transport.send(msg);

This uses the SMTP server specified in the properties for the session.
 

Now  set this bean and property in applicationContext.xml file

  <beans>
   <bean id="mailbean" class="roseindia.web.common.SendMail">
   <property name="strSmtp"><value>192.168.10.14</value></property>
    </bean>
   </beans>

Here we set the host name or IP of webserver. 

Defining constants---

package roseindia.web.common;

public class ProjectConstants {
public static String MAIL_BEAN="mailbean";

public static String FROM_MAIL="deepak@localhost";
}

Put the following code in which class from where you want to send mail--------

   //Retrieve the DAO Reference
   roseindia.web.common.SendMail mailBean = (roseindia.web.common.SendMail) 
   ServiceFinder.getContext(request).getBean(roseindia.web.common.ProjectConstants.MAIL_BEAN);

   String subject="Your username & password "; 

   String message="Hi,"+username;
  message+="\n Your username is "+username+".";
  message+="\n Your password is "+strPasswordEmail[0]+".";
  message+="\n Please login to the web site with your username and password.";
  message+="\n \n Thanks";
  message+="\n \n \n Regards";

   //Getting  FROM_MAIL from roseindia.web.common.ProjectConstants.FROM_MAIL

   String from=roseindia.web.common.ProjectConstants.FROM_MAIL;

   try{
  mailBean.sendMail(reciepent,subject,message,from);

  }catch(Exception e){
   System.out.println("Error in sending mail:"+e);
  }

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 21, 2008

Ask Questions?    Discuss: Send Mail Bean   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Ahmed
August 5, 2012
Send Mail Bean Error

Hi there, when I run the program on Eclipse, I get the following error: Error in sending mail:javax.mail.MessagingException: Could not connect to SMTP host: 192.168.10.14, port: 25 so to what should I change the host name or IP? I am using Tomcat-v7 server Thanks very much!
DMCA.com