Email User with attachemnt program

Posted on 2012-09-04
Last Modified: 2012-09-07

I am looking for a sample java progam which emails user with simple excel or text file attachemnt from local machine say C drive.
Any ideas, suggestions, sample code, links, source code highly appreciated. Thanks in advance
Question by:gudii9
    LVL 7

    Author Comment

    I tried this example from bel;ow link

    getting error like

    javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
      nested exception is:
 Connection refused: connect
          at com.sun.mail.smtp.SMTPTransport.openServer(
          at com.sun.mail.smtp.SMTPTransport.protocolConnect(
          at javax.mail.Service.connect(
          at javax.mail.Service.connect(
          at javax.mail.Service.connect(
          at javax.mail.Transport.send0(
          at javax.mail.Transport.send(
          at com.phh.SendEmail.main(
    Caused by: Connection refused: connect
          at Method)
          at com.sun.mail.util.SocketFetcher.createSocket(
          at com.sun.mail.util.SocketFetcher.getSocket(
          at com.sun.mail.smtp.SMTPTransport.openServer(
          ... 7 more
    please advise
    LVL 7

    Author Comment

    I tried this example from below link

    >>>Download the JAF 1.1 zip from the link given below:


    >>Steps to install Java Beans Activation Framework

    >>Unzip the archive.
    >>Set CLASSPATH to include the "activation.jar" file obtained from the download

    I could not find the activation jar in the downloaded zip to be included in the classpath. Please advise
    LVL 7

    Author Comment

    I even tried this program

    which is also not working. Please advise
    LVL 10

    Accepted Solution

    Try this with below jars in the classpath:
    - mail.jar
    - activation-1.1.jar

    Also refer your another thread:

    import java.util.*;
    import javax.mail.*;
    import javax.activation.*;
    import javax.mail.internet.*;
    public class SendAttachment {
        String smtpHost = ""; //smtp server address
        String smtpPort = "587"; //default is 25
        String mailContentType = "text/html";
    	boolean authRequired = true; //if the smtp server is require to authenticate user before sending mail
        String smtpUser = ""; //user required for authentication
        String smtpPassword = "my pass"; //password for authentication
        public static void main(String args[]) throws Exception {
            String from = "";
            String to = ""; //for multiple recipient separate the email by comma
            String cc = null; //for multiple recipient separate the email by comma
            String subject = "test subject";
            String message = "Hello how are you?";
            String file = "d:\\temp\\file.txt";  //assign null if attachment not needed
            System.out.println(new SendAttachment().sendMail(from, to, cc, subject, message, file));
        public String sendMail(String from, String to, String cc, String subject, String emailMessage, String file) {
            String lsMessage = "Mail Sent";
            if (smtpHost == null) {
                lsMessage = "Mail Server Host is not defined";
                return lsMessage;
            try {
                // General properties
                Properties loProps = new Properties();
                loProps.put("mail.transport.protocol", "smtp");
                loProps.put("", smtpHost);
                loProps.put("mail.smtp.port", smtpPort);
                Session session = null;
                if (authRequired) {
    				loProps.put("mail.smtp.auth", "true");
                    MailAuthenticator mailAuthenticator = new MailAuthenticator(smtpUser, smtpPassword);
                    session = Session.getInstance(loProps, mailAuthenticator);
                } else {
                    loProps.put("mail.smtp.auth", "false");
                    session = Session.getInstance(loProps, null);
                InternetAddress[] toAddr = getInetAddress(to);
                InternetAddress[] ccAddr = getInetAddress(cc);
                // Prepare Message
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(from));
                message.addRecipients(Message.RecipientType.TO, toAddr);
                if (ccAddr != null) message.addRecipients(Message.RecipientType.CC, ccAddr);
                // Message Body
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setContent(emailMessage, mailContentType);
                Multipart multipart = new MimeMultipart();
                //  Attachment
                if (file != null) {
    				File attachment = new File(file);
                    messageBodyPart = new MimeBodyPart();
                    FileDataSource loSource = new FileDataSource(attachment);
                    messageBodyPart.setDataHandler(new DataHandler(loSource));
                // Send message
                Transport transport = session.getTransport("smtp");
                transport.connect(smtpHost, smtpUser, smtpPassword);
                transport.sendMessage(message, toAddr);
                if (ccAddr != null) transport.sendMessage(message, ccAddr);
            } catch (Exception exception) {
                lsMessage = exception.getMessage();
            return lsMessage;
        public InternetAddress[] getInetAddress(String fsAddress) throws AddressException {
            if (fsAddress == null) return null;
            fsAddress = fsAddress.trim();
            if (fsAddress.equals("")) return null;
            String[] laAddress = stringToArray(fsAddress,",");
            ArrayList lvInetAddress = new ArrayList();
            InternetAddress[] laInetAddress = null;
            for (int liCtr = 0; liCtr < laAddress.length; liCtr++) {
                // Append the email address in lvInetAddress only when there is a not empty email address.
                if (laAddress[liCtr] != null && !laAddress[liCtr].equals("")) {
                    lvInetAddress.add(new InternetAddress(laAddress[liCtr]));
            // If the size of Internet Address is greater then zero then convert
            // it in to array of type InternetAddress and return it back to the calling method.
            if (lvInetAddress.size() > 0) {
                laInetAddress = new InternetAddress[lvInetAddress.size()];
            return laInetAddress;
    	class MailAuthenticator extends Authenticator {
            PasswordAuthentication moPasswordAuthentication;
            public MailAuthenticator(String fsUserName, String fsPassword) {
                moPasswordAuthentication = new PasswordAuthentication(fsUserName, fsPassword);
            public PasswordAuthentication getPasswordAuthentication(String lsUserName, String lsPassword) {
                return moPasswordAuthentication;
    	public String[] stringToArray(String fsString, String fsDelimiter)
    		if (fsString == null) return new String[0];
    		int liStart = 0;
    		ArrayList lvData = new ArrayList();
    		int liLen = fsDelimiter.length();
    		int liPos = fsString.indexOf(fsDelimiter, liStart);
    		while (liPos > -1)
    			lvData.add(fsString.substring(liStart, liPos).trim());
    			liStart = liPos + liLen;
    			liPos = fsString.indexOf(fsDelimiter, liStart);
    		int liSize = lvData.size();
    		String[] lsArray = new String[liSize];
    		return lsArray;

    Open in new window

    LVL 20

    Expert Comment

    by:Amitkumar Panchal
    Agree with pramodkrjsr. Try his solution.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
    Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
    Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
    This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

    794 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now