Wednesday, March 16, 2011

How to send email in java (swings)

Hello firiends,



In this blog we will see a small tutorial on sending mail using swings, sending mail using java is also
a simple task

Now we will see code in easy steps.

Step I : Get Required jars.

How to send email using java? or send email (swings) java.
For mail sending purpose  you require two jar files such as
1. Activation.jar
2. Mail.jar
  To download the Activation Jar        Click here to download Activation.jar
  To Download the Mail.Jar                Click here to download Mail.Jar
For mail sending purpose this jar files are very important download them from above link if the
above link won't work then you find it on google search.

ok friends now you have both of this jar files  i.e. Activation.jar & Mail.jar
now the code to send the mail.
here i have created this project using Net Beans 7.0.


Code is shown as below.

Step II: Design form as shown above.

 *Note: if you are looking for plane java then no need to create it just hard code values for fields like to,subject and message.

Step III: Create postMail method.

Create a class named SendMailUsingAuthentication.java and copy below code in it.

*Note: Remebmer to replace SMTP_AUTH_USER = "abc";  with your actual gmail email address
and   SMTP_AUTH_PWD  = "abc332";   with your actual gmail password.


package Mail;

/*
Some SMTP servers require a username and password authentication before you                     
can use their Server for Sending mail. This is most common with coupl e                                   
of ISP's who provide SMTP Address to Send Mail                                                                  
                                                                                                                                               
This Program gives any example on how to do SMTP Authentication                                        
(User and Password verification )                                                                                             
                                                                                                                                                      
This is a free source code and is provided as it is without any warranties and                             
it can be used in any your code for free .                                                                                  
                                                                                                                                                                    
Author : Sandeep                                                                                                                    
*/                                                                                                                                           
import javax.mail.*;                                                                                                                
import javax.mail.internet.*;                                                                                                    
import java.util.*;                                                                                                                    
                                                                                                                                                            
public class SendMailUsingAuthentication                                                                               
{                                                                                                                                            
  private static final String SMTP_HOST_NAME = "smtp.gmail.com";  // for google                
  private static final String SMTP_AUTH_USER = "abc";             // Username                        
  private static final String SMTP_AUTH_PWD  = "abc332";          // Password                     
                                                                                                                                             

  // Add List of Email address to who email needs to be sent to                                               
  public void postMail( 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.starttls.enable","true");                                                                     
     props.put("mail.smtp.host", SMTP_HOST_NAME);                                                        
     props.put("mail.smtp.auth", "true");                                                                                    

    Authenticator auth = new SMTPAuthenticator();                                                                
    Session session = Session.getDefaultInstance(props, auth);                                                 

    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);                                             
    // Setting the Subject and Content Type                                                                            
    msg.setSubject(subject);                                                                                                  
    msg.setContent(message, "text/plain");                                                                              
    Transport.send(msg);                                                                                                       
 }                                                                                                                                        


/**                                                                                                                                      
* SimpleAuthenticator is used to do simple authentication                                                     
* when the SMTP server requires it.                                                                                    
*/                                                                                                                                        
private class SMTPAuthenticator extends javax.mail.Authenticator                                        
{                                                                                                                                          

        @Override                                                                                                                   
    public PasswordAuthentication getPasswordAuthentication()                                             
    {                                                                                                                                      
        String username = SMTP_AUTH_USER;                                                                    
        String password = SMTP_AUTH_PWD;                                                                     
        return new PasswordAuthentication(username, password);                                             
    }                                                                                                                                       
}


Step III: Code for jFrame:

Declare variables as 
private static String emailMsgTxt = "";
private static String emailSubjectTxt = "";
private static String emailFromAddress = "";
// Add List of Email address to who email needs to be sent to
private static String[] emailList = new String[10];

Add Below code on Send_Button_Action_Performed.


        emailMsgTxt = txtarea_message.getText();
        emailSubjectTxt = txtsubject.getText();
        emailFromAddress = SendMailUsingAuthentication.SMTP_AUTH_USER;

        // Add List of Email address to who email needs to be sent to
        StringBuffer sb = new StringBuffer(txtto.getText());
        StringTokenizer st = new StringTokenizer(txtto.getText());
        int i = 0;
        while (st.hasMoreTokens()) {
            emailList[i] = st.nextToken(",");
            System.err.println(emailList[i]);
            i++;
        }
        String emailReceipeint[] = new String[i];
        for (int j = 0; j < i; j++) {
            emailReceipeint[j] = emailList[j];
            System.out.println("Actually emails are " + j);
        }


        SendMailUsingAuthentication smtpMailSender = new SendMailUsingAuthentication();
        try {
            smtpMailSender.postMail(emailReceipeint, emailSubjectTxt, emailMsgTxt, emailFromAddress);
        } catch (MessagingException ex) {
            Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Sucessfully Sent mail to All Users");


Now run your application!



Please leave a comment as Thanks if you found this post helpful


This is what send email using swings, I hope you all have understand If you have any queries please leave comment
 
Enjoy It.
Cheers!!!!!

free counters

9 comments:

  1. nice tutorial.....

    ReplyDelete
  2. I'm getting an error over this line of code in SendMailUsingAuthentication class

    Authenticator auth = new SMTPAuthenticator();

    Hint im getting is to create a new classSMTPAuthenticator PLS provide me some solution

    ReplyDelete
  3. Yes it is class and you need to create it. see below


    /**
    * SimpleAuthenticator is used to do simple authentication
    * when the SMTP server requires it.
    */
    private class SMTPAuthenticator extends javax.mail.Authenticator
    {

    @Override
    public PasswordAuthentication getPasswordAuthentication()
    {
    String username = SMTP_AUTH_USER;
    String password = SMTP_AUTH_PWD;
    return new PasswordAuthentication(username, password);
    }
    }
    }

    ReplyDelete
    Replies
    1. Thanks it works
      Thank you very much
      I created the class
      SMTPAuthenticator extends javax.mail.Authenticator
      as you told
      I had to change the access specifier of the variable to public static final String SMTP_AUTH_USER instead of private static final String SMTP_AUTH_USER

      Delete
  4. Well, i follow the steps completely but im getting an error while running my program:


    javax.mail.AuthenticationFailedException
    Plz can anyone help me:(

    ReplyDelete