Email sending with an attachment example

Click here to download eclipse supported ZIP file



This is email.properties properties file and these properties are used in the application.




mail.subject=SubjectGoesHere
mail.smtp.host=smtp.sendgrid.net
port=25
to.address=XXXXX@gmail.com
cc.address=XXX@gmail.com,YYY@gmail.com
bcc.address=XXX@gmail.com
from.address=XXX@gmail.com
username=username
password=password
mail.smtp.auth=true
mail.smtp.starttls.enable=true
attachment.mail.body=Hi, <br><br> Please find the file attached for the date : : APPEND_DATE. <br><br>Regards,<br> XXXXX


This is AppInit.java file having the source code to execute business logic.



 

    
package com.cv.mail;

import java.util.Properties;

import org.apache.log4j.Logger;

/**
 @author Chandra Vardhan
 *
 */
public class AppInit {

  private static final Logger LOGGER = Logger.getLogger(AppInit.class);

  static Properties mailProperties = new Properties();
  static {
    mailProperties = readPropertiesFile();
  }
  private static Properties readPropertiesFile() {
    Properties props = new Properties();
    try {
      LOGGER.debug("email.properties file read successfully...");
      props.load(AppInit.class.getClassLoader().getResourceAsStream("email.properties"));
    catch (Exception e) {
      LOGGER.error("Problem while reading email properties file : : " + e.getMessage());
    }
    return props;
  }

}


This is EmailUtils.java file having the source code to execute business logic.



 

    
package com.cv.mail;

import java.io.File;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;

/**
 @author  Chandra Vardhan
 *
 */
public class EmailUtils {

  private static final Logger LOGGER = Logger.getLogger(EmailUtils.class);

  public static void sendEmail(final Properties emailProperties, String content, final File attachment) {
    LOGGER.debug("In EmailUtils.sendEmail(- -) method");
    try {
      if (emailProperties != null && !emailProperties.isEmpty()) {
        // Get the session object
        final String userName = (StringemailProperties.get("username");
        final String password = (StringemailProperties.get("password");
        String log = "Mail with attachment sent successfully...";
        Session session = Session.getInstance(emailProperties, new javax.mail.Authenticator() {
          protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
          }
        });
        if (content != null) {
          content = "<p><span face=\"Calibri\" style=\"font-family: Calibri;\"><font size=\"4\">" + content + "</font></p>";
        }
        Message message = new MimeMessage(session);
        if (attachment != null) {
          log = "Mail with attachment sent successfully...";
          // Create the message part
          BodyPart messageBodyPart = new MimeBodyPart();
          // Create a multipar message
          messageBodyPart.setContent(content, "text/html");
          Multipart multipart = new MimeMultipart();
          // Set text message part
          multipart.addBodyPart(messageBodyPart);
          // Part two is attachment
          messageBodyPart = new MimeBodyPart();
          DataSource source = new FileDataSource(attachment);
          messageBodyPart.setDataHandler(new DataHandler(source));
          messageBodyPart.setFileName(attachment.getName());
          multipart.addBodyPart(messageBodyPart);
          // Send the complete message parts
          message.setContent(multipart);
        else {
          message.setContent(content, "text/html");
        }
        log = "Mail sent successfully...";
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse((StringemailProperties.get("to.address")));
        message.setRecipients(Message.RecipientType.CC,
            InternetAddress.parse((StringemailProperties.get("cc.address")));
        message.setRecipients(Message.RecipientType.BCC,
            InternetAddress.parse((StringemailProperties.get("bcc.address")));
        message.setFrom(new InternetAddress((StringemailProperties.get("from.address")));
        message.setSubject((StringemailProperties.get("mail.subject"));
        // Now set the actual message
        Transport.send(message);
        LOGGER.debug(log);
      else {
        LOGGER.error("Please provide email properties. There are no email properties.");
      }
    catch (

    AddressException e) {
      LOGGER.error("Problem while sending mail...");
      e.printStackTrace();
    catch (MessagingException e) {
      LOGGER.error("Problem while sending mail...");
      e.printStackTrace();
    }
    LOGGER.debug("Out EmailUtils.sendEmail(- -) method");
  }
}


This is TestEmail.java file having the source code to execute business logic.



 

    
/**
 
 */
package com.cv.mail;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 @author Chandra Vardhan
 *
 */
public class TestEmail {

  /**
   @param args
   */
  public static void main(String[] args) {
    //Send normal email
    EmailUtils.sendEmail(AppInit.mailProperties,"Content"null);
    
    File file = new File("test.txt");
    try {
      file.createNewFile();
    catch (IOException e) {
      e.printStackTrace();
    }
    String body = AppInit.mailProperties.getProperty("attachment.mail.body");
    body = body.replace("APPEND_DATE"""+new Date());
    //Send attached mail    
    EmailUtils.sendEmail(AppInit.mailProperties,body, file);
  
  }

}


This is pom.xml file having the entries of dependency jars and information to build the application .



	
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.email</groupId> <artifactId>EmailSending</artifactId> <version>1.0</version> <packaging>jar</packaging> <name>Maven Quick Start Archetype</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4</version> </dependency> </dependencies> </project>


This is log4j.properties file having the entries for logging the information into the console/file.




#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


No comments:

Post a Comment