Sunday 14 June 2009

Sending Email with Java Mail with attachments Example

Here I am sharing my EmailManager class that handles Email. Hope you find it useful.
package com.console.app.service;

import com.console.app.mtgapi.ApiRequest;
import com.console.app.mtgapi.ApiResponse;
import com.console.core.biz.MtEmailAuthenticator;
import com.sun.mail.smtp.SMTPSSLTransport;
import java.util.Properties;
import javax.ejb.Stateless;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

/**
 *
 * @author Farouk Alhassan
 */
@Stateless
public class EmailManagerImpl implements EmailManager {
  
  private static String SMTP_HOST_SERVER = "plus.smtp.mail.yahoo.com";
  
  private static String POP3_SERVER = " plus.pop.mail.yahoo.com";
  
  private static String SMTP_PORT = "465";
  
  private static String POP3_PORT = "995";
  
  private static String ACCOUNT_NAME ="MY_ACCOUNT_NAME";
  
  private static String EMAIL_ADDRESS = "MY_ACCOUNT_NAME@yahoo.com";
  
  private static String ACCOUNT_PASSWORD = "MY_PASSWORD";
  
  private static String USE_AUTHENTICATION = "true";
  
  private static String SMTP_USE_SSL = "true";
  
  private static String POP3_USE_SSL = "true";

  public void sendEmail(String to,
          String subject, String messageBody ) throws
          MessagingException, AddressException {

    // Setup mail server
    Properties props = System.getProperties();
    props.put("mail.smtps.host", SMTP_HOST_SERVER);
    props.put("mail.smtps.port", SMTP_PORT);
    props.put("mail.smtps.auth", USE_AUTHENTICATION);
    props.put("mail.smtps.user", ACCOUNT_NAME);

    // Get a mail session
    Session session = Session.getDefaultInstance(props,null);
      //new MtEmailAuthenticator());
    session.setDebug(true);

    // Define a new mail message 
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(EMAIL_ADDRESS));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);

    // Create a message part to represent the body text
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(messageBody,"text/html");

    //use a MimeMultipart as we need to handle the file attachments 
    Multipart multipart = new MimeMultipart();

    //add the message body to the mime message
    multipart.addBodyPart(messageBodyPart);

    // Put all message parts in the message 
    message.setContent(multipart);

    // Send the message
    SMTPSSLTransport tr = (SMTPSSLTransport) session.getTransport("smtps");
    tr.connect(SMTP_HOST_SERVER, ACCOUNT_NAME, ACCOUNT_PASSWORD);
    message.saveChanges();
    tr.sendMessage(message, message.getAllRecipients());
    tr.close();
  }

  protected void addAtachments(String[] attachments, Multipart multipart)
          throws MessagingException, AddressException {
    for (int i = 0; i <= attachments.length - 1; i++) {
      String filename = attachments[i];
      MimeBodyPart attachmentBodyPart = new MimeBodyPart();

      //use a JAF FileDataSource as it does MIME type detection
      DataSource source = new FileDataSource(filename);
      attachmentBodyPart.setDataHandler(new DataHandler(source));

      //assume that the filename you want to send is the same as the
      //actual file name - could alter this to remove the file path
      attachmentBodyPart.setFileName(filename);

      //add the attachment
      multipart.addBodyPart(attachmentBodyPart);
    }
  }
}


Feel free to comment and let me know how I could have done this better