Loading
Send Email with Attachments

Java Quick Notes

Refresh Your Java - Before Java Interview

We are Agile, believe in less Documentation - Only Quick notes (Java Interview Questions) of Java/J2ee Read more....


Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet

Go to SiteMap

Q)  Send Email with Attachments


Ans)

Sending Email with Attachments By using Java Mail:

This MailNotification Class holds a method that sends the emails with attachments
by using Java Mail API.

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

 public class MailNotificationSender  {
  private Session mailConn = null;
  private String msgFromDefault = null;
  private String mailUser = null;
  private String mailPass = null;
  private String mailHost = null;
  private static Logger logger = Logger.getLogger(MailNotificationSender.class.getName());
 
  /**
   * this constrcutor config the message server details
   *
   * @throws NotificationException
   */  
  public MailNotificationSender() throws NotificationException  {
    try {
      Properties mailprops = new Properties();
      MailAuthenticator mailAuth = null;
      msgFromDefault = PropertyReader.readProperty(
                NotificationConstant.MAIL_FROM_DEFAULT);
      mailUser = PropertyReader.readProperty(
                NotificationConstant.MAIL_USER);
      mailPass = PropertyReader.readProperty(
        NotificationConstant.MAIL_PASS);
      mailHost = PropertyReader.readProperty(
        NotificationConstant.MAIL_HOST)!=null?NotificationPropertyReader.readProperty(
        NotificationConstant.MAIL_HOST):
       InetAddress.getLocalHost().getHostName();
      //initialize mail properties
      mailprops.setProperty("mail.smtp.host",mailHost);
      //if username and password provided, create an authenticator
      if(mailUser != null && mailPass != null) {
        mailAuth = new MailAuthenticator(mailUser,mailPass);
      }
      //Create the mail connection
      //mailConn = Session.getDefaultInstance(mailprops,mailAuth);
   mailConn = Session.getDefaultInstance(mailprops,null);
    }catch(Exception e){
      //log the error
      error("init()", e.getMessage());
      e.printStackTrace();
    }
  }
 
 
  /**
   * Sends email from SMTP server
   *
   * @param String msgTo
   * @param String msgFrom
   * @param String msgReplyTo
   * @param String msgSubject
   * @param String msgContent
   * @param String msgContentType
   * @param Vector msgAttachments
   */
  public void sendMailWithAttachments(String msgTo,
    String msgFrom, String msgSubject, String msgContent,
    String msgContentType, List msgAttachments, String msgReplyTo) {
   try{
      MimeBodyPart mbpFileAttachment = null;
      MimeMultipart mp = new MimeMultipart();
      Message msg = new MimeMessage(mailConn);
      if(msgFrom == null|| msgFrom.length() == 0) msgFrom = msgFromDefault;
      msg.setFrom(new InternetAddress(msgFrom));
      // replyTo address
      if ( msgReplyTo != null && msgReplyTo.length() != 0 ) {
       msg.setReplyTo( InternetAddress.parse(msgReplyTo, false) );
   }
      //to address
      msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(msgTo, false));
      //subject
      msg.setSubject(msgSubject);
      //message body
      MimeBodyPart mbpBodyText = new MimeBodyPart();
      mbpBodyText.setContent(msgContent, msgContentType);
      mp.addBodyPart(mbpBodyText);
      //Add the attachments
      Iterator iterator = msgAttachments.iterator();
      while(iterator.hasNext()){
        Object msgAttach = iterator.next();
        FileDataSource fds = null;
        File attachFile = null;
        if(msgAttach instanceof File) {
          attachFile = (File)msgAttach;
        }else if(msgAttach instanceof String){ //this is added by Siva Malladi
          //for attaching files from DT, EX. PSS Waiver Form
          attachFile = new File((String)msgAttach);
        }
        if(attachFile!=null&&attachFile.exists()){
          mbpFileAttachment = new MimeBodyPart();
          fds = new FileDataSource(attachFile);
          mbpFileAttachment.setDataHandler(new DataHandler(fds));
          mbpFileAttachment.setFileName(fds.getName());
          mp.addBodyPart(mbpFileAttachment);

        }
      }
      msg.setContent(mp);
      Transport.send(msg);
    }catch(Exception e){
      //log the error
      error("sendMailWithAttachments()",e.toString());
    }
  }
 }



Back to top

------------------------- We hope you got necessary Info On -----------------------------------------

Send Email with Attachments


Send Email with Attachments

-------------------------------------------------------------------------------------------------------



Face Book
Request for a Mock Interview/Training

Get a PDF

Face Book
Same look (Read) on any device, this is Ads free