Please disable your adblock and script blockers to view this page

Search this blog

Showing posts with label Activation.jar. Show all posts
Showing posts with label Activation.jar. Show all posts

Monday 12 January 2015

Send eMail and attachement from any SMTP server using JavaMail in Oracle ADF


The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications- JavaMail API

This post is about sending eMail and attachments from any SMTP (Simple Mail Transfer Protocol) as Gmail or any other server (mail.awasthiashish.com)
You can read my previous post about mail integration with ADF that was specifically about using Gmail Server
Gmail Integration with Oracle ADF using Java Mail API 

So all basic configuration is described in previous post , now in this post i am only writing a java method to send mail and attachments


Don't forget to download these 2 jar files
  1.mail.jar 2. Activation.jar- Download
Add both jar files to project library path and then use this method 
Necessary packages to import -


import java.util.ArrayList;
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.NoSuchProviderException;
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;


Helper method (JavaCode) to send simple eMail and eMail with attachment-

    /**Method to send mail from any SMTP server using JavaMail API
     * Provide Correct Parameters
     * @return
     * @param msg- Email Message Body
     * @parsm subject- Subject of Email
     * @param FromUser- Email Id of Sender
     * @param ToUser- Email Id of Reciever
     * @param pwd- Password of sender's email address
     * @param hostName- Host Name of Mail server (smtp.gmail.com)
     * @param isAnyAtchmnt- "Y" for yes there is an attachement and "N" for no attachment
     * @param fileNamePath- abolute path of file on server if there is any attachement
     */
    public String sendMail(String msg, String subject, String FromUser, ArrayList<String> ToUser, String pwd,
                           String hostName, String isAnyAtchmnt, ArrayList<String> fileNameNPath) {
        // Setting Properties
        Properties emailProperties = new Properties();
        emailProperties.put("mail.smtp.host", hostName);
        emailProperties.put("mail.smtp.auth", "true");
        emailProperties.put("mail.smtp.starttls.enable", "true");
        //Login Credentials
        final String user = FromUser; //change accordingly
        final String password = pwd; //change accordingly
        //Authenticating...
        Session session = Session.getInstance(emailProperties, new javax.mail.Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        });

        //1) create MimeBodyPart object and set your message content
        MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(user));
            for (String email : ToUser) {
                System.out.println("Mail Id is-" + email);
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            }
            message.setSubject(subject);

            BodyPart messageBody = new MimeBodyPart();

            messageBody.setContent(msg, "text/html");

            // If there is any attachment to send
            //5) create Multipart object and add MimeBodyPart objects to this object
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBody);

            if ("Y".equalsIgnoreCase(isAnyAtchmnt)) {
                //2) create new MimeBodyPart object and set DataHandler object to this object


                for (String path : fileNameNPath) {
                    MimeBodyPart messageBodyPart2 = new MimeBodyPart();
                    System.out.println("Exact path--->" + path);
                    DataSource source = new FileDataSource(path);
                    messageBodyPart2.setDataHandler(new DataHandler(source));
                    // System.out.println("FileName is-"+path.substring(path.lastIndexOf("//")+1, path.length()));
                    messageBodyPart2.setFileName(path.substring(path.lastIndexOf("//") + 2, path.length()));
                    multipart.addBodyPart(messageBodyPart2);
                }

                //6) set the multiplart object to the message object
                message.setContent(multipart);
                message.saveChanges();
            }
            //If there is plain eMail- No Attachment
            else {
                message.setContent(msg, "text/html"); //for a html email
            }
        } catch (MessagingException e) {
        }

        Transport transport = null;


        try {
            transport = session.getTransport("smtp");
        } catch (NoSuchProviderException e) {
            System.out.println("No such Provider Exception");
        }

        try {
            transport.connect(hostName, FromUser, pwd);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

            System.out.println("Email sent successfully.");
            return "Y";
        } catch (MessagingException e) {
            System.out.println("Messaging Exception" + e);
            return "N";
        }

    }


Call this method in your ADF Application to send simple mail or mail with attachment, this is just like plug n play , provide correct parameters and use

Thanks :) Happy Learning

Thursday 18 April 2013

Gmail Integration with Oracle ADF using Java Mail API

Gmail is a free secure webmail provided by google, can be accessed by using POP3 or IMAP4 protocol
we have option to integrate Gmail with Java using Java Mail API and I have tried same in Oracle
ADF.
I have developed an application that can send mail (with Attachements) using Gmail in Oracle ADF,
using bounded TaskFlow.

  • First , in bounded taskflow ,a login page is created, and a page to send mail is created
  • Now you can get values from page and use in bean- So I am not going to write these things
  • Integration points starts when you get mail server properties- Managed Bean Code
  • You have to use 2 JAR ,inorder to use Java Mail API
  1.mail.jar 2. Activation.jar- Download
    Properties emailProperties;

    public void setMailServerProperties() {
    String emailPort = "587"; //gmail's smtp port
    emailProperties = System.getProperties();
    emailProperties.put("mail.smtp.port", emailPort);
    emailProperties.put("mail.smtp.auth", "true");
    emailProperties.put("mail.smtp.starttls.enable", "true");

    }

  • Now you have to create your message (With or Without attachments)--
     

  • public void createEmailMessageWidtAtchmnt() throws AddressException, MessagingException {
    toWhom = toBind.getValue().toString();
    subject = subjectBind.getValue().toString();
    messagae = messageBind.getValue().toString();
    String[] toEmails = { toWhom };

    String emailSubject = subject;
    String emailBody = messagae;

    mailSession = Session.getDefaultInstance(emailProperties, null);
    emailMessage = new MimeMessage(mailSession);

    for (int i = 0; i < toEmails.length; i++) {
    emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
    }

    emailMessage.setSubject(emailSubject);

    //1) create MimeBodyPart object and set your message content
    BodyPart messageBodyPart1 = new MimeBodyPart();
    messageBodyPart1.setText(emailBody);

    emailMessage.setContent(emailBody, "text/html"); //for a html email


    }
  • here I am getting values from page component binding so don't get confused by this- toBind
    subjectBind, messageBind are component binding of page




  • Code snippet to create mail with attachements, you have to do little change in createEmailMessageWidtAtchmnt() to add files in mail . This code browse files from D drive
    of system .

  • //1) create MimeBodyPart object and set your message content
    BodyPart messageBodyPart1 = new MimeBodyPart();
    messageBodyPart1.setText(emailBody);

    //2) create new MimeBodyPart object and set DataHandler object to this object
    MimeBodyPart messageBodyPart2 = new MimeBodyPart();

    String filename = "D://" + file_name; //change accordingly
    System.out.println("Exact path--->" + filename);
    DataSource source = new FileDataSource(filename);
    messageBodyPart2.setDataHandler(new DataHandler(source));
    messageBodyPart2.setFileName(filename);


    //5) create Multipart object and add MimeBodyPart objects to this object
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart1);
    multipart.addBodyPart(messageBodyPart2);

    //6) set the multiplart object to the message object
    emailMessage.setContent(multipart);
  • To add files in mail in ADF you have to use af:inputFile component, and create a ValueChangeListener on component that get fileName when you browse any file from D drive of your system .

  • private String file_name;

    public void uploadedFileAttachmentVCE(ValueChangeEvent valueChangeEvent) {
    UploadedFile file = (UploadedFile)valueChangeEvent.getNewValue();
    file_name = file.getFilename();
    }
  • From login page you will get login emailId and password, that is set in managed bean code to authenticate user- and send mail

  • public void sendEmail() {

    String emailHost = "smtp.gmail.com";
    String fromUser = emailId; //just the id alone without @gmail.com
    String fromUserEmailPassword = pwd;
    Transport transport = null;
    try {
    transport = mailSession.getTransport("smtp");
    } catch (NoSuchProviderException e) {
    System.out.println("No such Provider Exception");
    }
    try {
    transport.connect(emailHost, fromUser, fromUserEmailPassword);
    transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
    transport.close();
    StringBuilder msgEmail = new StringBuilder("Email Sent");
    FacesMessage msg = new FacesMessage(msgEmail.toString());
    msg.setSeverity(FacesMessage.SEVERITY_INFO);
    FacesContext.getCurrentInstance().addMessage("No Network Error !", msg);
    System.out.println("Email sent successfully.");
    } catch (MessagingException e) {
    System.out.println("somthing went wrong-->Messaging Exception");

    }

    }