Saturday, April 9, 2011

How to send email with attachment in Java



Hello friends,

In the previous post we have seen How to send email using java (swings) now we will see how to send email with attachment.

Steps.

1. Create a java application
2. Create a java class
3. Download the Mail.Jar and activation.Jar files.
4. Use the following code in to your class file.


Following is the code to send email via java.
send mail using java requires two jar files (i.e Activation.jar, Mail.jar)
Links to download the libraries.

activation.jar
mail.jar



Steps in writing code.

1. Imports to be used.

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

these are the imports. First two are contained in java package and rest three are in the Javax Package for that u will require mail.jar and activation.jar libraries .




public class AttachExample {

for the purpose of the smtp authentication you require to enter your account username and password and this account will be used to send the mail.

private static final String SMTP_AUTH_USER ="abc";
private static final String SMTP_AUTH_PWD = "pqr123"; // Password

public static void main(String args[]) throws Exception {


Host name of your email service provider if your account is on the gmail then you can use as follows.

String host = "smtp.gmail.com";

this will be your email Id
String from = "abc@gmail.com";

to array stores the list of receipents you can write multiple email ID.

String[] to = {"xxxx@domain.com"};

filename variable contains the name of the file to be attached. It should be a zipped file or any file.

String filename = "AttachFile.txt";

These instance of file is used to get the current directory of your running java application.

File f=new File("..");
System.out.println(f.getAbsolutePath());

Instance of Properties is used to store the System Property.

// Get system properties
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");

here you have enabled the authentication.

Authenticator auth = new SMTPAuthenticator();

Created a session

Session session = Session.getDefaultInstance(props, auth);

Created a Instance of message

Message message = new MimeMessage(session);

message.setFrom(new InternetAddress(from));

convert the receipents address to the Internet Address

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

attach all the fields to the message.

message.setRecipients(Message.RecipientType.TO, toAddress);
message.setSubject("Hello JavaMail Attachment");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here's the file");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);

Send your Email with the attachment.

try {
Transport.send(message);
} catch (SendFailedException sfe) {
message.setRecipients(Message.RecipientType.TO, sfe.getValidUnsentAddresses());
Transport.send(message);

}



}
/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
private static 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);
}

}
}



Now the complete code is shown as here



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

public class AttachExample {

private static final String SMTP_AUTH_USER ="abc";
private static final String SMTP_AUTH_PWD = "pqr123"; // Password

public static void main(String args[]) throws Exception {
String host = "smtp.gmail.com";
String from = "abc@gmail.com";
String[] to = {"xxxx@domain.com"};
String filename = "AttachFile.txt";

File f=new File("..");
System.out.println(f.getAbsolutePath());

//Instance of Properties is used to store the System Property.

// Get system properties
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
convert the receipents address to the Internet Address
InternetAddress[] toAddress = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++) {
toAddress[i] = new InternetAddress(to[i]);
}
message.setRecipients(Message.RecipientType.To,toAddress);
message.setSubject("Hello JavaMail Attachment");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here's the file");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
try {
Transport.send(message);
} catch (SendFailedException sfe) {
message.setRecipients(Message.RecipientType.TO, sfe.getValidUnsentAddresses());
Transport.send(message);

}



}
/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
private static 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);
}

}
}



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

Friday, February 25, 2011

MySql database backup (Swing) java

How to take MYSQL database backup from java swings?

Hello friends,
Here i have given explaination about how to take backup of mysql database from java swings below example i have created with the help of NetBeans 6.1, we will describe this step bye step.
often you required to take backup of mysql databases from your swing application. You can use mysqldump to take Mysql backup here i have try to simplify it.

if you are using Net Beans IDE then this will be very easy.

Step 1. - create a jframe in swing as shown as following figure





Step2: write below code under event of choose button

choose menu is to select the folder where you wish to take your backup sql file.
I have achieved it by using JFileChooser component of swing.

 txtbackuppath.setText(getBackUpPath());

//getBackUpPath() function is as shown below.


  public static String getBackUpPath() {

         String backUpPath = "";
         JFileChooser fc = null;
         if (fc == null) {
                fc = new JFileChooser();
                fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                fc.setAcceptAllFileFilterUsed(false);
        }
        int returnVal = fc.showDialog(null, "Open");
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            backUpPath = file.getAbsolutePath();
        }
       return backUpPath;
}



Hello friends uptill now we have seen that how we got the path where we can store the backup file of mysql database.
//above function is used to get the back up path dynamically by using jFileChooser component.
Now to connect with MySql we have required parameters such as Username, Password and database
name whose backup have to be taken it all shown in above figure.

Now we will see directly the code which is required for backup purpose.
this code is written under the backup button which is shown in above figure.

Step3: write below code under event of backup button



   String backuppath=txtbackuppath.getText();
   String Database =txtdatabasename.getText();
   String Password =txtpassword.getText();
   String user=txtuser.getText();
   Backup b = new Backup();
   try
  {
       byte[] data = b.getData("localhost", "3306", user,   Password, Database).getBytes();
       File filedst = new File(backuppath+"\\"+Database+".zip");
       FileOutputStream dest = new FileOutputStream(filedst);
       ZipOutputStream zip = new ZipOutputStream(
       new BufferedOutputStream(dest));
       zip.setMethod(ZipOutputStream.DEFLATED);
       zip.setLevel(Deflater.BEST_COMPRESSION);
       zip.putNextEntry(new ZipEntry("data.sql"));
       zip.write(data);
       zip.close();
       dest.close();
      JOptionPane.showMessageDialog(null, "Back Up Successfully."+"\n"+"For Database: "+Database+"\n        "+"On Dated: ","Database BackUp Wizard",JOptionPane.INFORMATION_MESSAGE);
   }catch (Exception ex){
    JOptionPane.showMessageDialog(null, "Back Up Failed."+"\n"+"For Database: "+Database+"\n "+"On     Dated: ","Database BackUp Wizard",JOptionPane.INFORMATION_MESSAGE);
    ex.printStackTrace();
  }

Hello friend this is what the code which takes the database backup in zipped format. it requires one more class file whose code i have given below

//It will require a "BackUp.java" file.


BackUp.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Backup
{

    private static ResultSet res;
    private static Connection con;
    private Statement st;
    private int BUFFER = 99999;
    public String getData(String host, String port, String user, String password, String db) {
        String Mysqlpath = getMysqlBinPath(user, password, db);
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("yaha dekho");
        }
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + db, user, password);
            st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,                                                                          ResultSet.CONCUR_UPDATABLE);
        } catch (Exception e) {
            System.out.print("I am here yaaar");
            e.printStackTrace();
        }


        System.out.println(Mysqlpath);
        Process run = null;
        try {
            System.out.println(Mysqlpath + "mysqldump --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + " --compact --complete-insert --extended-insert " + "--skip-comments --skip-triggers " + db);
            run = Runtime.getRuntime().exec(Mysqlpath + "mysqldump --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + "  " + "--skip-comments --skip-triggers " + db);
        } catch (IOException ex) {
            // Logger.getLogger(Backup.class.getName()).log(Level.SEVERE, null, ex);
        }


        InputStream in = run.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        StringBuffer temp = new StringBuffer();
  

        int count;
        char[] cbuf = new char[BUFFER];
        try {
            while ((count = br.read(cbuf, 0, BUFFER)) != -1) {
                temp.append(cbuf, 0, count);
            }
        } catch (IOException ex) {
            Logger.getLogger(Backup.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            br.close();
            in.close();
        } catch (IOException ex) {
            Logger.getLogger(Backup.class.getName()).log(Level.SEVERE, null, ex);
        }
        return temp.toString();
    }

// Mysql path is required to locate the bin folder inside it because it contains the Mysqldump which performs a //main role while taking backup.
/*Function to find MySql Path*/
    public  String getMysqlBinPath(String user, String password, String db) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("yaha dekho");
        }
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + db, user, password);
            st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        } catch (Exception e) {
            System.out.print("I am here yaaar");
            e.printStackTrace();
        }


        String a = "";

        try {
            res = st.executeQuery("select @@basedir");
            while (res.next()) {
                a = res.getString(1);
            }
        } catch (Exception eee) {
            eee.printStackTrace();
        }
        a = a + "bin\\";
        System.err.println("Mysql path is :" + a);
        return a;
    }
}








//Above project is done in Netbeans if any one wants it's full source code can contact to me or they can leave //comment.

Download Source Code from Github Click here to download







Wednesday, February 16, 2011

how to export jtable data to excel file

Hello friends,
following is the  function which helps to export tables data to the excel file.
exportTable()  function takes two parameter one is table and another one is the file name

eg. exportTable(table, new File("D:\tabledata.xls"));

public void exportTable(JTable table, File file) throws IOException {
            TableModel model = table.getModel();
            FileWriter out = new FileWriter(file);
            for(int i=0; i < model.getColumnCount(); i++) {
        out.write(model.getColumnName(i) + "\t");
            }
            out.write("\n");

            for(int i=0; i< model.getRowCount(); i++) {
        for(int j=0; j < model.getColumnCount(); j++) {
            out.write(model.getValueAt(i,j).toString()+"\t");
            }
            out.write("\n");
        }

        out.close();
        System.out.println("write out to: " + file);
}

If any queries and any suggestions regarding this please mention

Wednesday, December 29, 2010

get Mysql path from java

import java.sql.*;
import javax.sql.*;

public class MysqlPathFinderDemo{

public static void main(String args[]){
String dbtime;
String dbUrl = "jdbc:mysql://your.database.domain/yourDBname";
String dbClass = "com.mysql.jdbc.Driver";
String query = "Select * FROM users";

try {

      Class.forName("com.mysql.jdbc.Driver");
      Connection con = DriverManager.getConnection (dbUrl);
      Statement stmt = con.createStatement();
res=Myconnection.st.executeQuery("select @@datadir");
String Mysqlpath="";
      while(res.next()){
          Mysqlpath=res.getString(1) ;
      } 
Mysqlpath=Mysqlpath.replace("Data", "bin"); 
System.err.println("Mysql path is :"+a);
   }catch(Exception ee){
}
 }
} 

Thursday, December 23, 2010

Java - How to print table with multi line header and footer

PrinterJob job = PrinterJob.getPrinterJob();
MessageFormat[] header = new MessageFormat[3];
header[0] = new MessageFormat("");
header[1] = new MessageFormat("line 1");
header[2] = new MessageFormat("line 2");

MessageFormat[] footer = new MessageFormat[2];
footer[0] = new MessageFormat("footer 1");
footer[1] = new MessageFormat("footer 2");
job.setPrintable(new MyTablePrintable(tblmunim, PrintMode.FIT_WIDTH, header, footer));

    if (job.printDialog())
      try {
        System.out.println("Calling PrintJob.print()");
        job.print();
        System.out.println("End PrintJob.print()");
      }
      catch (PrinterException pe) {
        System.out.println("Error printing: " + pe);
      }

Here is MyTablePrintable class  MyPrintable.java