• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 494
  • Last Modified:

Email User with attachemnt program

Hi,

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
0
gudii9
Asked:
gudii9
  • 3
1 Solution
 
gudii9Author Commented:
I tried this example from bel;ow link

http://www.tutorialspoint.com/java/java_sending_email.htm

getting error like

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
  nested exception is:
      java.net.ConnectException: Connection refused: connect
      at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934)
      at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
      at javax.mail.Service.connect(Service.java:295)
      at javax.mail.Service.connect(Service.java:176)
      at javax.mail.Service.connect(Service.java:125)
      at javax.mail.Transport.send0(Transport.java:194)
      at javax.mail.Transport.send(Transport.java:124)
      at com.phh.SendEmail.main(SendEmail.java:51)
Caused by: java.net.ConnectException: Connection refused: connect
      at java.net.PlainSocketImpl.socketConnect(Native Method)
      at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
      at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
      at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
      at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
      at java.net.Socket.connect(Socket.java:529)
      at java.net.Socket.connect(Socket.java:478)
      at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288)
      at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
      at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
      ... 7 more
please advise
0
 
gudii9Author Commented:
I tried this example from below link

http://www.roseindia.net/javamail/Introduction-to-Java-Mail-API.shtml

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

>>http://java.sun.com/javase/technologies/desktop/javabeans/jaf/downloads/index.html

>>Steps to install Java Beans Activation Framework

>>Unzip the jaf-1_1_1.zip 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
0
 
gudii9Author Commented:
I even tried this program

http://www.roseindia.net/javamail/SendAttachment.shtml


which is also not working. Please advise
0
 
Pramod KumarCommented:
Try this with below jars in the classpath:
- mail.jar
- activation-1.1.jar

Also refer your another thread:
http://www.experts-exchange.com/Programming/Languages/Java/J2EE/Q_27853070.html

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

public class SendAttachment {

    String smtpHost = "smtp.logix.in"; //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 = "abc@ab.com"; //user required for authentication
    String smtpPassword = "my pass"; //password for authentication

    public static void main(String args[]) throws Exception {
        String from = "me@abc.com";
        String to = "pramodkrjsr@gmail.com"; //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("mail.smtp.host", 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.setSubject(subject);

            // Message Body
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(emailMessage, mailContentType);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);

            //  Attachment
            if (file != null) {
				File attachment = new File(file);
                messageBodyPart = new MimeBodyPart();
                FileDataSource loSource = new FileDataSource(attachment);
                messageBodyPart.setDataHandler(new DataHandler(loSource));
                messageBodyPart.setFileName(attachment.getName());
                multipart.addBodyPart(messageBodyPart);
            }

            // 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()];
            lvInetAddress.toArray(laInetAddress);
        }
        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);
		}
		lvData.add(fsString.substring(liStart).trim());

		int liSize = lvData.size();
		String[] lsArray = new String[liSize];
		lvData.toArray(lsArray);
		return lsArray;
	}

}

Open in new window

0
 
Amitkumar PSr. ConsultantCommented:
Agree with pramodkrjsr. Try his solution.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now