A JavaMail & File Attachment Example

This tutorial is a continuation on JavaMail

It shows a java class that allows you to send e-mails with a file attached

 

/**
 * File Name:   SendEmail.java
 * @date        June 21 2001
 * @author      Siomara Pantarotto
 * Description: Definition of Class SendEmail.
 * 				Sends email messages using SMTP protocal.
 * 				Uses JavaBean Activation Foundation.
 * 				Complies to JavaMail API standards.
 *				This version sends attached file.
 **/
 import java.io.*;
 import java.util.*;
 import javax.mail.*;
 import javax.activation.*;
 import javax.mail.internet.*;
 public class SendEmail{
    private String mailHost		= null;
    private String fromAddress	= null;
    private String toAddress	= null;
    private String subject		= null;
    private String messageTxt	= null;
    private String contentType	= null;
    private String fileName		= null;
    /**
    * Default constructor - No argument for Java Bean Requirement
    **/
    SendEmail()
    {
    }
   /**
    * Constructor
    * @params mailHost     - SMTP server name
    * @params fromAddress  - From address in RFC822 format
    * @params toAddress    - To address in RFC822 format
    * @params subject      - Subject for the email message
    * @params messageTxt   - Email template file
    * @params contentType  - Content type for the email message
    * @params fileName	   - File name to be attached to email message
    **/
    SendEmail(String mailHost,String fromAddress, String toAddress,
    				String subject, String messageTxt, String contentType,
                    String fileName)
    {
        this.mailHost		= mailHost;
        this.fromAddress	= fromAddress;
        this.toAddress		= toAddress;
        this.subject		= subject;
        this.messageTxt		= messageTxt;
        this.contentType	= contentType;
        this.fileName		= fileName;
    }
   /**
    * Constructor
    * @params mailHost     - SMTP server name
    * @params fromAddress  - From address in RFC822 format
    **/
    SendEmail(String mailHost,String fromAddress)
    {
        this.mailHost    = mailHost;
        this.fromAddress = fromAddress;
    }
   /**
    * Set and Get methods for attribute mailHost
    *
    * @params mailHost  - SMTP server name
    **/
    public void setMailHost(String mailHost)
    {
        this.mailHost    = mailHost;
    }
   /* @return mailHost */
    public String getMailHost()
    {
        return this.mailHost;
    }
   /**
    * Set and Get methods for attribute fromAddress
    *
    * @params fromAddress  - From address in RFC822 format
    */
    public void setFromAddress(String fromAddress)
    {
        this.fromAddress    = fromAddress;
    }
    /* @return fromAddress */
    public String getFromAddress()
    {
        return this.fromAddress;
    }
   /**
	* Set and Get methods for attribute toAddress
    *
    * @params toAddress  - To address in RFC822 format
    */
    public void setToAddress(String toAddress)
    {
        this.toAddress      = toAddress;
    }
    /* @return toAddress */
    public String getToAddress()
    {
        return this.toAddress;
    }
   /**
   	* Set and Get methods for attribute subject
    *
    * @params subject - Subject for the email message
    */
    public void setSubject(String subject)
    {
        this.subject = subject;
    }
    /* @return subject */
    public String getSubject()
    {
        return this.subject;
    }
   /**
    * Set and Get methods for attribute messageTxt
    *
    * @params messageTxt - Message text for the email message
    */
    public void setMessageTxt(String messageTxt)
    {
        this.messageTxt  = messageTxt;
    }
    public String getMessageTxt()
    {
        return this.messageTxt;
    }
   /**
    * Set and Get methods for attribute contentType
    *
    * @params contentType  - Content type for the email message
    */
    public void setContentType(String contentType)
    {
        this.contentType = contentType;
    }
    public String getContentType()
    {
        return this.contentType;
    }
    /**
    * Set and Get methods for attribute fileName
    *
    * @params fileName  - File that is attached to the message
    */
    public void setFileName(String fileName)
    {
        this.fileName = fileName;
    }
    public String getFileName()
    {
        return this.fileName;
    }
   /**
    * Sends email notifications
    *
    * @param msg - Message to send
    */
    public void sendMessage(String mailText)
    {
        boolean debug = false;
        Properties props = new Properties();
        props.put("mail.smtp.host", this.getMailHost());
        Session session = Session.getDefaultInstance(props,null);
        session.setDebug(debug);
        try
        {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(this.getFromAddress()));
            message.setRecipients(Message.RecipientType.TO,
            	InternetAddress.parse(this.getToAddress(), false));
            message.setSubject(this.getSubject());
    		/**
			 * Create the message - part one
			 */
			// Create first body part
    		BodyPart messageBodyPart = new MimeBodyPart();
    		// Fill the message
    		messageBodyPart.setText(this.getMessageTxt());
    		// Create a Multipart
    		Multipart multipart = new MimeMultipart();
		    // Add part one - message
    		multipart.addBodyPart(messageBodyPart);
    		/**
			 * Create the attachment - part two
			 */
		    // Create second body part
			messageBodyPart = new MimeBodyPart();
    		// Get the attachment
    		DataSource source = new FileDataSource(this.getFileName());
    		// Set the data handler to the attachment
    		messageBodyPart.setDataHandler(new DataHandler(source));
    		// Set the filename
    		messageBodyPart.setFileName(this.getFileName());
    		// Add part two - attachment
    		multipart.addBodyPart(messageBodyPart);
    		// Put all parts in message
    		message.setContent(multipart);
			// Send the message
            Transport.send(message);
        }
        catch(Exception e )
        {
            e.printStackTrace();
            System.exit(-1);
        }
        props = null;
    }
}

This is a servlet to test the class

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class SendMailServlet extends HttpServlet {
  /**
   * Process the HTTP Post request
   */
  public void service(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
    HttpSession session = request.getSession(true);
    SendEmail sendEmail = new SendEmail();
    sendEmail.setMailHost("Snhexch02");
    sendEmail.setFromAddress("[email protected]");
    sendEmail.setToAddress("[email protected]");
    sendEmail.setSubject("Testando mail");
    sendEmail.setMessageTxt("blab blab bla ...... good bye");
    sendEmail.setContentType("text/plain");
    sendEmail.setFileName("c:\\aaa.txt");
    sendEmail.sendMessage(sendEmail.getMessageTxt());
  }
}

 

 

 

1