Java email with Attachment

import java.util.Date;
import java.util.Properties;
import java.util.StringTokenizer;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class AttachmentMailer
{
    private String host    = "";
    private String to      = "";
    private String from    = "";
    private String subject = "";
    private String body    = "";

    public AttachmentMailer(String pHost)
    {
        host = pHost;
    }

    public void setTo(String pTo)
    {
        to = pTo;
    }

    public void setFrom(String pFrom)
    {
        from = pFrom;
    }

    public void setSubject(String pSub)
    {
        subject = pSub;
    }

    public void setBody(String pBody)
    {
        body = pBody;
    }

    /*
     * This method sends an email for the given parameters. It returns a boolean
     * value depending on the status of the mail sending process.
     */

    public boolean sendMailWithAttachment()
    {
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        Session session = Session.getDefaultInstance(props, null);

        try
        {
            // create a message
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            StringTokenizer stkz = new StringTokenizer(to, ",");
            InternetAddress[] address = new InternetAddress[stkz.countTokens()];
            int i = 0;
            while (stkz.hasMoreTokens())
            {
                address[i] = new InternetAddress(stkz.nextToken().trim());
                i++;
            }
            msg.setRecipients(Message.RecipientType.TO, address);
            msg.setSubject(subject);
            msg.setSentDate(new Date());
            msg.setText(body);
           
            String filename = "emaployees.xls";//change accordingly  
            DataSource source = new FileDataSource(filename);  
            msg.setDataHandler(new DataHandler(source));  
           

            Transport.send(msg);
            return true;
        }
        catch (MessagingException mex)
        {
            mex.printStackTrace();
            System.out.println();
            Exception ex = mex;
            do
            {
                if (ex instanceof SendFailedException)
                {
                    SendFailedException sfex = (SendFailedException) ex;
                    Address[] invalid = sfex.getInvalidAddresses();
                    if (invalid != null)
                    {
                        System.err.println("In-valid Email Addresses");
                        if (invalid != null)
                        {
                            for (int i = 0; i < invalid.length; i++)
                                System.out.println("Address = " + invalid[i]);
                        }
                    }
                    Address[] validUnsent = sfex.getValidUnsentAddresses();
                    if (validUnsent != null)
                    {
                        System.err.println("Email not sent to Addresses");
                        if (validUnsent != null)
                        {
                            for (int i = 0; i < validUnsent.length; i++)
                                System.out.println("Address = " + validUnsent[i]);
                        }
                    }
                }
            }
            while ((ex = ((MessagingException) ex).getNextException()) != null);
            return false;
        }
    }

    public static void main(String args[])
    {
        String pHost = "";
        String pTo = "";
        String pFrom = "";
        String pSubject = "";

        // provide the smtp host below
        pHost = "smtp.techdive.in";

        // to send email to multiple users, provide email ids as comma separated values
        pTo = "user1@techdive.in,user2@techdive.in";
        pFrom = "admin@techdive.in";
        pSubject = "Test Mail - Techdive";
        String pBodyq = "This is a Test Mail from Techdive.in";

        AttachmentMailer eMail = new AttachmentMailer(pHost);
        eMail.setTo(pTo);
        eMail.setFrom(pFrom);
        eMail.setSubject(pSubject);
        eMail.setBody(pBodyq);
        eMail.sendMailWithAttachment();
    }
}

Technology: 

Search