Subversion Repositories SmartDukaan

Rev

Rev 5138 | Rev 9703 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.utils;

import java.io.File;
import java.security.Security;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
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 javax.mail.util.ByteArrayDataSource;

public class GmailUtils {

    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final String SMTP_PORT = "465";
    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    
    public GmailUtils(){
    }
    
    public void sendSSLMessage(String recipients[], String subject, String message, final String from, final String password, String filename) throws MessagingException {
        try {
            Message msg = prepareMessage(recipients, subject, from, password);
            //Create the multi-part object to hold the text and attachment parts
            Multipart multipart = new MimeMultipart();
            // create the message part 
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            //Part 1: Text message
            messageBodyPart.setText(message);
            multipart.addBodyPart(messageBodyPart);
            //Part 2: Attachment
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            String[] names = filename.split("/");
            messageBodyPart.setFileName(names[names.length - 1]);
            multipart.addBodyPart(messageBodyPart);
            // Put parts in message
            msg.setContent(multipart);
            Transport.send(msg);
        } catch (Exception e) {
            // If there is any error with normal mail sending, try diving receipients across domains
            if (hasMultipleDomains(recipients)) {
                for (List<String> subReceipients : getReceipientsPerDomain(recipients).values()) {
                    sendSSLMessage(subReceipients.toArray(new String[0]), subject, message, from, password, filename);
                }

                return;
            }
            
            throw new MessagingException(e.getMessage(), e);
        }
    }

    /**
     * @param recipients
     * @return
     */
    private Map<String, List<String>> getReceipientsPerDomain(String[] recipients) {
        Map<String, List<String>> result = new HashMap<String, List<String>>();
        for (String recipient : recipients) {
            String domain = extractDomainFromEmailAddress(recipient);

            if (!result.containsKey(domain)) {
                result.put(domain, new ArrayList<String>());
            }

            result.get(domain).add(recipient);
        }

        return result;
    }

    /**
     * @param recipients
     * @return
     */
    private boolean hasMultipleDomains(String[] recipients) {
        String domain = extractDomainFromEmailAddress(recipients[0]);
        for (String recipient : recipients) {
            if (!domain.equals(extractDomainFromEmailAddress(recipient))) {
                return true;
            }
        }

        return false;
    }

    private String extractDomainFromEmailAddress(String recipient) {
        return recipient.split("@")[1];
    }

    public void sendSSLMessage(String recipients[], String subject, String message, final String from, final String password, List<File> files) throws MessagingException {
        try {
            Message msg = prepareMessage(recipients, subject, from, password);
            
            //Create the multi-part object to hold the text and attachment parts
            Multipart multipart = new MimeMultipart();
            
            // create the message part 
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            //Part 1: Text message
            messageBodyPart.setText(message);
            multipart.addBodyPart(messageBodyPart);

            //Part 2: Attachment
            for (File file : files) {
                DataSource source = new FileDataSource(file);
                String[] names = file.getAbsolutePath().split("/");
                messageBodyPart = new MimeBodyPart();
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(names[names.length - 1]);
                multipart.addBodyPart(messageBodyPart);
            }

            // Put parts in message
            msg.setContent(multipart);
            Transport.send(msg);
        } catch (Exception e) {
            // If there is any error with normal mail sending, try diving receipients across domains
            if (hasMultipleDomains(recipients)) {
                for (List<String> subReceipients : getReceipientsPerDomain(recipients).values()) {
                    sendSSLMessage(subReceipients.toArray(new String[0]), subject, message, from, password, files);
                }

                return;
            }
            
            throw new MessagingException(e.getMessage(), e);
        }
    }

    @SuppressWarnings("restriction")
    private Message prepareMessage(String[] recipients, String subject,
            final String from, final String password) throws AddressException,
            MessagingException {
        boolean debug = true;

        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        
        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(from, password);
                    }
                });

        session.setDebug(debug);

        Message msg = new MimeMessage(session);
        
        //Set the from address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        //Set the recipients
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        //Setting the Subject
        msg.setSubject(subject);
        return msg;
    }
    
    public static void main(String args[]) throws Exception {
        String[] sendTo = { "mandeep.dhir@shop2020.in", "mandeep.dhir@gmail.com", "mandeepcse07@yahoo.co.in", "anupam.singh@shop2020.in" };
        String emailSubjectTxt = "Another test from gmail";
        String emailMsgTxt = "Test Message Contents";
        String emailFromAddress = "mandeep.dhir@shop2020.in";
        String password = "";
        String filename = "/home/mandeep/virtual_warehouse.sql";

        GmailUtils utils = new GmailUtils();
        utils.sendSSLMessage(sendTo, emailSubjectTxt, emailMsgTxt, emailFromAddress, password, filename);
        System.out.println("Sucessfully Sent mail to All Users");
    }
}