Please disable your adblock and script blockers to view this page

Search this blog

Showing posts with label Email Validation. Show all posts
Showing posts with label Email Validation. 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 17 April 2014

ViewObject Validation rules for transient attributes (Model level validation in ADF)

Hello All,
this post is about model level validation for transient attributes, often we need to apply some common types of validation on transient attributes (as for negative value, for email, for phone number)
in ADF ViewObject there is a editor for validation rules for transient attributes, so now see how to use that editor and rules


  • Create a fusion web application and prepare model layer using Departments table of HR schema


  • Then create a transient attribute in viewObject and you can see that Validation Rules tab appears only in case of transient attribute



  • Now click on add icon to add new validation rule for attribute, you can see there are multiple types for that validation rule 





  • In this post i have used Compare and Regular Expression rules, suppose i have to check that value of transient attribute must not be 100 , so for that rule will be like this, and write a proper message for failure handling 



  • Now run your BC4J tester and check , a window with error message appears there in case of failure


  • You can also check this validation on your page, some more- i have added one more transient field for Email Address and applied a regular expression to validate this field (ADF by default provides regular expression for Email and Phone Number pattern for others you can use your own pattern)


  • After model level configurations , i have dropped Departments ViewObject on page as ADF form, here you can see both validation are working 




Cheers :-) Happy Learning

Wednesday 21 November 2012

Custom Validator in Oracle ADF (JSF Validator), Email Validation Using Regex

Validation is very important part of any programming language, when we visit any website's registration form it says "This field is mandatory" or "Email id is not valid","Password doesn't match", these all are validations

What is a Validator-
A computer program or piece of code that checks syntax or value of any field according to a predefined condition is called Validator
Validators are used in every programming/scripting language.

How to Use Custom Validator in ADF Forms-
This is not complex to use validator in ADF forms, means in .jsff or in .jspx pages. Suppose we have a field of EmailId on form and we want to add custom email id validator on this field

To add validator in a field follow these steps

  • Select the field in Form
af:inputText to enter email id

  •  Now go to property inspector and Select Validator,it is empty by default
Create Validator method in managed bean
  • Now click on Validator edit in property inspector and create a validator in ManagedBean of taskflow




 
  • It will look like this- Default Custom Validator 
This validator method validates value of inputText

  •  Now we will add custom code to validate EmailId field in this validator

  1.     public void emailValidator(FacesContext facesContext, UIComponent uIComponent, Object object) {
  2.         if(object!=null){
  3.             String name=object.toString();
  4.             String expression="^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
  5.             CharSequence inputStr=name;
  6.             Pattern pattern=Pattern.compile(expression);
  7.             Matcher matcher=pattern.matcher(inputStr);
  8.             String msg="Email is not in Proper Format";
  9.             if(matcher.matches()){
  10.                
  11.             }
  12.             else{
  13.                 throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,msg,null));
  14.             }
  15.         }
  16.     }

  • Now when we run this page, we can see validation
Regex to check Email Id format and in case of failure it show validation message