Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Tuesday, February 21, 2017

Create Thubmnail / Image From Each Page of a PDF Using Java

It is very important to make some thumbnails from pdf in our application. Using java it is now very easy to do this task. You have to open your pdf using java program then you can set which page (0...n) you want to make to thumbnail. Then you can save that as image to your server or desktop machine.

To complete this task you need to download PDFRenderer-0.9.1.jar.

You can download whole package from here.

Sample java code:

package com.pkm;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by pritom on 26/12/2016.
 */
public class ThumbnailFromPdf {
    public static void main(String[] args) throws Exception {
        File file = new File("src/com/pkm/PDF.pdf");
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
        FileChannel fileChannel = randomAccessFile.getChannel();
        ByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
        PDFFile pdfFile = new PDFFile(byteBuffer);
        PDFPage pdfPage = pdfFile.getPage(0);
        Rectangle rectangle = new Rectangle(0, 0, (int) pdfPage.getBBox().getWidth(), (int) pdfPage.getBBox().getHeight());
        Image image = pdfPage.getImage(rectangle.width, rectangle.height, rectangle, null, true, true);
        ImageIO.write((RenderedImage) image, "png", new File("src/com/pkm/PDF.png"));
    }
}

Sample output would be like something depends on your pdf file:


 

Monday, December 19, 2016

Java Send Email Using Office 365 OAuth Connection

Download source code from here

To get oauth access token & other information used in this code snippet visit:
http://pritomkumar.blogspot.com/2016/11/write-php-app-to-get-outlook-office-365.html



package com.pkm.office_oauth;

import com.google.gson.Gson;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by pritom on 18/12/2016.
 */
public class JavaSendMailUsingOffice365OAuth {
    private static final String OFFICE_ACCESS_TOKEN = "xxxxx";
    private static String mailUUID = "";

    /**
     * API URL
     * https://msdn.microsoft.com/en-us/office/office365/api/complex-types-for-mail-contacts-calendar#MessageResource
     * https://msdn.microsoft.com/en-us/office/office365/api/extended-properties-rest-operations
     */

    public static void main(String[] args) throws Exception {
        send();
    }

    private static void send() throws Exception {
        Map<String, Object> message = new HashMap<>();
        message.put("Subject", "Some Sample Subject");
        message.put("Body", getBody());
        addRecipients(message);
        addCustomHeader(message);
        addAttachment(message);

        Map<String, Map> messagePayload = new HashMap<>();
        messagePayload.put("Message", message);

        Gson gson = new Gson();
        String messageAsJson = gson.toJson(messagePayload);

        List<String> headers = new ArrayList<>();
        headers.add("Authorization: Bearer " + OFFICE_ACCESS_TOKEN);
        headers.add("Accept: application/json");
        headers.add("Content-Type: application/json");
        headers.add("Content-Length: " + messageAsJson.length());

        String url = "https://outlook.office.com/api/v2.0/me/sendmail";
        JavaSendMailUsingOffice365OAuth.Response response = executeSend(url, messageAsJson, headers);
        System.out.println("STATUS_CODE=" + response.httpCode);
        if (response.httpCode == 202) {
            System.out.println("MESSAGE SENT\r\n\r\nTRY TO RETRIEVE MAIL SENT");
            filterMessageSent();
        }
        else {
            System.out.println(response);
        }
    }

    private static void filterMessageSent() throws Exception {
        String query = "SingleValueExtendedProperties/Any" +
                URLEncoder.encode("(ep: ep/PropertyId eq 'String {" + mailUUID + "} Name CUSTOM_HEADER_1' and ep/Value eq 'CUSTOM_HEADER_1_VALUE_" + mailUUID + "')", "UTF-8");
        String select = "Id,InternetMessageId";
        String url = "https://outlook.office.com/api/v2.0/me/messages?$filter=" + query + "&$select=" + select;

        List<String> headers = new ArrayList<>();
        headers.add("Authorization: Bearer " + OFFICE_ACCESS_TOKEN);
        headers.add("Accept: application/json");
        JavaSendMailUsingOffice365OAuth.Response response = executeSend(url, "", headers);
        if (response.httpCode == 200) {
            Map result = new Gson().fromJson(response.httpResponse, Map.class);
            result = (Map) ((List) result.get("value")).get(0);
            System.out.println("UNIQUE_OFFICE_MAIL_ID_OF_SEND_EMAIL=" + result.get("Id"));
            System.out.println("UNIQUE_MESSAGE_ID_OF_SEND_EMAIL=" + result.get("InternetMessageId"));
        }
    }

    private static void addCustomHeader(Map<String, Object> message) {
        List<Map> list = new ArrayList<>();
        mailUUID = UUID.randomUUID().toString();

        Map<String, String> val1 = new HashMap<>();
        val1.put("PropertyId", "String {" + mailUUID + "} Name CUSTOM_HEADER_1");
        val1.put("Value", "CUSTOM_HEADER_1_VALUE_" + mailUUID);

        list.add(val1);

        message.put("SingleValueExtendedProperties", list);
    }

    private static JavaSendMailUsingOffice365OAuth.Response executeSend(String url, String messageAsJson, List<String> headers) throws Exception {
        int httpCode = 0, timeOutMilli = 1000 * 30;;
        String httpResponse = "", responseMessage = "";

        HttpURLConnection connection = null;
        try {
            System.setProperty("https.protocols", "TLSv1.1,SSLv3,SSLv2Hello");
            connection = (HttpURLConnection) new URL(url).openConnection();
            if (messageAsJson.length() > 0) {
                connection.setRequestMethod("POST");
            }
            else {
                connection.setRequestMethod("GET");
            }
            connection.setDoOutput(true);
            connection.setConnectTimeout(timeOutMilli);
            connection.setReadTimeout(timeOutMilli);
            connection.setRequestProperty("Pragma", "no-cache");

            for (int i = 0; i < headers.size(); i++) {
                String header = headers.get(i);
                connection.setRequestProperty(header.substring(0, header.indexOf(":")), header.substring(header.indexOf(":") + 1));
            }

            if (messageAsJson.length() > 0) {
                connection.setDoInput(true);
                OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
                streamWriter.write(messageAsJson);
                streamWriter.flush();
                streamWriter.close();
            }

            httpCode = connection.getResponseCode();
            responseMessage = connection.getResponseMessage();
            InputStream inputStream = null;

            if (httpCode >= 200 && httpCode <= 399) {
                inputStream = connection.getInputStream();
            }
            else {
                inputStream = connection.getErrorStream();
            }

            if (inputStream != null) {
                Writer writer = new StringWriter();
                char[] buffer = new char[1024];
                Reader reader = new BufferedReader(new InputStreamReader(inputStream));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
                httpResponse = writer.toString();
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
            responseMessage = ex.getMessage();
        }
        return new JavaSendMailUsingOffice365OAuth.Response(httpCode, responseMessage, httpResponse);
    }

    private static Map<String, Object> getBody() throws Exception {
        Map<String, Object> body = new HashMap<>();

        body.put("ContentType", "HTML");
        body.put("Content", new String("<DIV><B>HTML BODY CONTENT</B></DIV>".getBytes(), "UTF-8"));

        return body;
    }

    private static void addRecipients(Map<String, Object> message) {
        Map<String, Map> recipientMap = new HashMap<>();
        Map<String, String> recipientAddress = new HashMap<>();
        recipientAddress.put("Address", "pritom@xxxxx.com");
        recipientMap.put("EmailAddress", recipientAddress);

        List<Map> recipients = new ArrayList<>();
        recipients.add(recipientMap);

        message.put("ToRecipients", recipients);
    }

    private static void addAttachment(Map<String, Object> message) throws Exception {
        List<Map> attachments = new ArrayList<>();

        File file = new File("src/com/pkm/office_oauth/Attachment_Image_1.png");
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] toByte = new byte[(int) file.length()];
        fileInputStream.read(toByte);
        fileInputStream.close();

        file = new File("src/com/pkm/office_oauth/Attachment_Pdf_1.pdf");
        fileInputStream = new FileInputStream(file);
        toByte = new byte[(int) file.length()];
        fileInputStream.read(toByte);
        fileInputStream.close();

        Map<String, Object> attachment = new HashMap<>();
        attachment.put("@odata.type", "#Microsoft.OutlookServices.FileAttachment");
        attachment.put("Name", file.getName());
        attachment.put("ContentBytes", encodeBase64(toByte));

        attachments.add(attachment);
        message.put("Attachments", attachments);
    }

    private static String encodeBase64(byte[] bytes) throws Exception {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encodeBuffer(bytes);
    }

    private static class Response {
        int httpCode = 0;
        String httpResponse = "", responseMessage = "";

        public Response(int httpCode, String responseMessage, String httpResponse) {
            this.httpCode = httpCode;
            this.responseMessage = responseMessage;
            this.httpResponse = httpResponse;
        }

        public String toString() {
            Map<String, Object> output = new HashMap<>();
            output.put("httpCode", httpCode);
            output.put("responseMessage", responseMessage);
            output.put("httpResponse", httpResponse);
            return new Gson().toJson(output);
        }
    }
}

Sunday, December 18, 2016

Send Email Using Google OAuth & Java

Download source code & required jars from here

For get access token & google user id click here


package com.pkm.google_auth;

import com.google.api.client.googleapis.GoogleUtils;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.MessagePartHeader;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.ByteArrayOutputStream;
import java.util.Properties;

/**
 * Created by pritom on 18/12/2016.
 */
public class SendMail {
    private static final String USER_ID = "118224585672607576118";
    private static final String ACCESS_TOKEN = "ya29.Ci-4A700L53csid7qv6786780mbRqI8hdwesj7H2RSRnBizwfWFUY0pzYsx_xa-XZA";

    public static void main(String[] args) throws Exception {
        sendMail();
    }

    private static void sendMail() throws Exception {
        Properties props = new Properties();
        Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {

        });
        MimeMessage message = new MimeMessage(mailSession);

        message.setSubject("Test subject", "UTF-8");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("pritom@xxxxx.com", "Pritom Kumar"));

        Multipart multipart = new MimeMultipart();
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent("<DIV><B>BOLD HTML BODY</B></DIV>", "text/html");
        multipart.addBodyPart(messageBodyPart);

        message.addHeader("CUSTOM_HEADER_1", "CUSTOM_HEADER_1_VALUE");
        message.addHeader("CUSTOM_HEADER_2", "CUSTOM_HEADER_2_VALUE");

        message.setContent(multipart );

        GoogleCredential credential = new GoogleCredential().setAccessToken(ACCESS_TOKEN);
        Gmail gmail = new Gmail.Builder(_createHttpTransport(), _createJsonFactory(), credential).build();

        com.google.api.services.gmail.model.Message email = createMessageWithEmail(message);
        email = gmail.users().messages().send(USER_ID, email).execute();
        String emailID = email.getId(), messageID = getUniqueMessageIDByEMailId(emailID);
        System.out.println("EMAIL_SEND_WITH_GOOGLE_MAIL_ID=" + emailID);
        System.out.println("EMAIL_SEND_WITH_UNIQUE_MAIL_ID=" + messageID);
    }

    private static String getUniqueMessageIDByEMailId(String emailID) throws Exception {
        GoogleCredential credential = new GoogleCredential().setAccessToken(ACCESS_TOKEN);
        Gmail gmail = new Gmail.Builder(_createHttpTransport(), _createJsonFactory(), credential).build();
        com.google.api.services.gmail.model.Message message = gmail.users().messages().get(USER_ID, emailID).execute();
        for (MessagePartHeader messagePartHeader : message.getPayload().getHeaders()) {
            if (messagePartHeader.getName().equalsIgnoreCase("Message-ID")) {
                emailID = messagePartHeader.getValue().substring(1, messagePartHeader.getValue().length() - 1);
            }
        }
        return emailID;
    }

    private static com.google.api.services.gmail.model.Message createMessageWithEmail(MimeMessage email) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        email.writeTo(baos);
        String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
        com.google.api.services.gmail.model.Message message = new com.google.api.services.gmail.model.Message();
        message.setRaw(encodedEmail);
        return message;
    }

    private static HttpTransport _createHttpTransport() throws Exception {
        return new NetHttpTransport.Builder()
                .trustCertificates(GoogleUtils.getCertificateTrustStore())
                .build();
    }

    private static JsonFactory _createJsonFactory() {
        return new JacksonFactory();
    }
}

Saturday, December 17, 2016

How to convert Map / Object to Bytes and save to internal storage and read back

package com.pkm;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author PRITOM
 */
public class MapObjectToByteArrayAndSaveToFile {
    public static void main(String[] args) throws Exception {
        Map<Integer, String> data = new HashMap<Integer, String>();
        data.put(1, "hello");
        data.put(2, "world");
        System.out.println(data.toString());
        store(data);
        data = (Map<Integer, String>) load();
        System.out.println(data.toString());
    }
    
    public static Object load() throws Exception {
        FileInputStream fileInputStream = new FileInputStream("object.txt");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        return objectInputStream.readObject();
    }
    
    public static void store(Object data) throws Exception {
        FileOutputStream fileOutputStream = new FileOutputStream("object.txt");
        ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
        outputStream.writeObject(data);
        outputStream.close();
    }
}

Friday, November 25, 2016

Java: Reading Email & Attachments From Different Email Server Using Javamail API

Download required jar for java mail from here.

Code snippet


package com.pritom.src;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.SortTerm;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.search.*;
import java.io.File;
import java.util.*;

/**
 * @author PRITOM
 * @date 2016-11-25
 */
public class ReadEmailFromServer {
    public static void main(String[] args) {
        gmail();
        //bleep();
        //yahoo();;
        //office();
    }

    private static void office() {
        String PROTOCOL = "imaps", HOST = "outlook.office365.com", USER = "xxxxx@outlook.com",
                PASSWORD = "xxxxx", ENCRYPTION_TYPE = "tls", PORT = "993";
        readEmail(PROTOCOL, HOST, USER, PASSWORD, ENCRYPTION_TYPE, PORT);
    }

    private static void yahoo() {
        String PROTOCOL = "imaps", HOST = "mail.yahoo.com", USER = "xxxxx@yahoo.com",
                PASSWORD = "xxxxx", ENCRYPTION_TYPE = "tls", PORT = "993";
        readEmail(PROTOCOL, HOST, USER, PASSWORD, ENCRYPTION_TYPE, PORT);
    }

    private static void bleep() {
        String PROTOCOL = "imaps", HOST = "bleep.xxxxx.com", USER = "pritom@xxxxx.com",
                PASSWORD = "xxxxx", ENCRYPTION_TYPE = "tls", PORT = "993";
        readEmail(PROTOCOL, HOST, USER, PASSWORD, ENCRYPTION_TYPE, PORT);
    }

    private static void gmail() {
        String PROTOCOL = "imaps", HOST = "imap.gmail.com", USER = "xxxxx@gmail.com",
                PASSWORD = "xxxxx", ENCRYPTION_TYPE = "tls", PORT = "993";
        readEmail(PROTOCOL, HOST, USER, PASSWORD, ENCRYPTION_TYPE, PORT);
    }

    private static void readEmail(String PROTOCOL, String HOST, String USER, String PASSWORD, String ENCRYPTION_TYPE, String PORT) {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", PROTOCOL);
        if(ENCRYPTION_TYPE.length() > 0 && !ENCRYPTION_TYPE.equalsIgnoreCase("none")) {
            if(PROTOCOL.equalsIgnoreCase("imap")) {
                props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                props.setProperty("mail.imap.socketFactory.fallback", "false");
                props.setProperty("mail.imap.ssl.enable", "true");
                props.setProperty("mail.imap.socketFactory.port", PORT.length() > 0 ? PORT : "993");
                if(ENCRYPTION_TYPE.equalsIgnoreCase("tls")) {
                    props.setProperty("mail.imap.starttls.enable", "true");
                }
            }
            else if(PROTOCOL.equalsIgnoreCase("pop3")) {
                props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                props.setProperty("mail.pop3.socketFactory.fallback", "false");
                props.setProperty("mail.pop3.ssl.enable", "true");
                props.setProperty("mail.pop3.socketFactory.port", PORT.length() > 0 ? PORT : "995");
                if(ENCRYPTION_TYPE.equalsIgnoreCase("tls")) {
                    props.setProperty("mail.pop3.starttls.enable", "true");
                }
            }
        }
        try {
            Session session = Session.getInstance(props, null);
            Store store = session.getStore();
            store.connect(HOST, USER, PASSWORD);
            printAllFolders(store);
            IMAPFolder inbox = (IMAPFolder) store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);

            SortTerm[] sortTerms = new SortTerm[1];
            sortTerms[0] = SortTerm.ARRIVAL;
            Message[] messages = inbox.getSortedMessages(sortTerms, getSearchCriteria());

            int maxReadNumber = 1;
            int total = messages.length > maxReadNumber ? maxReadNumber : messages.length;
            println("\nTotal_Email = " + messages.length);
            boolean ascending = false;
            for (int index = 0; index < total; index++) {
                int message_index = ascending ? index : messages.length - index - 1;
                Message message = messages[message_index];
                String subject = message.getSubject();
                println("-------------------------------------------------------------------------------------------");
                println("-------------------------------------------------------------------------------------------");
                println("------------------" + (index + 1) + "/" + messages.length + "----------------------" + subject);
                println("-------------------------------------------------------------------------------------------");
                println("-------------------------------------------------------------------------------------------");
                printAllHeaders(message);
                if (message.getContent() instanceof String) {
                    println("\tContent---------------Type=" + message.getContentType());
                    String body = message.getContent().toString();
                    body = body.length() > 100 ? body.substring(0, 100) + "..." : body;
                    println("\t\t" + toSingleLine(body));
                }
                else {
                    Map output = processMultipart((Multipart) message.getContent());
                    Object[] keys = output.keySet().toArray();
                    for (int i = 0; i < keys.length; i++) {
                        println("\t" + keys[i].toString().toUpperCase() + "-------------------------------------------");
                        if (keys[i].toString() == "attachments") {
                            List attachments = (List) output.get("attachments");
                            for (int j = 0; j < attachments.size(); j++) {
                                Map attachment = (Map) attachments.get(j);
                                /* You can save attachments to your local machine by uncomment line below */
                                //String toFile = saveFileFromEmailAttachment(attachment);
                                //println("File_Saved_To=" + toFile);
                                println("\t\tFile_Name=" + attachment.get("fileName"));
                            }
                        }
                        else {
                            String body = output.get(keys[i].toString()).toString().trim();
                            body = body.length() > 100 ? body.substring(0, 100) + "..." : body;
                            println("\t\t[[[" + toSingleLine(body) + "]]]");
                        }
                    }
                }
                if (total == index + 1) {
                    println("-------------------------------------------------------------------------------------------");
                    println("-------------------------------------------------------------------------------------------");
                    println("-------------------------------------------------------------------------------------------");
                }
            }
            inbox.close(false);
            store.close();
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static void printAllFolders(Store store) throws Exception {
        println("Folders:::");
        Folder[] folders = store.getDefaultFolder().list();
        for (Folder folder : folders) {
            println("\t" + folder.getFullName());
            for (Folder subFolder : folder.list()) {
                println("\t\t" + subFolder.getFullName());
            }
        }
    }

    private static void printAllHeaders(Message message) throws Exception {
        Enumeration enumeration = message.getAllHeaders();
        while (enumeration.hasMoreElements()) {
            Header header = (Header) enumeration.nextElement();
            boolean show = !header.getName().startsWith("X-") && !header.getName().equals("Received");
            show = show && !header.getName().startsWith("Authentication-") && !header.getName().startsWith("DKIM-");
            if (show) {
                println("\t" + header.getName() + "===" + toSingleLine(header.getValue()));
            }
        }
    }

    private static SearchTerm getSearchCriteria() throws Exception {
        if (true) {
            //return null;
            //return new FlagTerm(new Flags(Flags.Flag.SEEN), false);
            //return new MessageIDTerm("CAD-oc7fMFqioVurtMPnGm63mWAA51wELBaLhtm38zvthTv0+DQ@mail.gmail.com");
        }
        FlagTerm unread = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        FromTerm fromTerm = new FromTerm(new InternetAddress("pritomkucse@gmail.com"));

        Calendar cal = Calendar.getInstance();
        /* Set date to 1 day back from now */
        cal.roll(Calendar.DATE, false);
        ReceivedDateTerm latest = new ReceivedDateTerm(DateTerm.GT, cal.getTime());
        SearchTerm andTerm = new AndTerm(unread, latest);

        SearchTerm notFromTerm = new NotTerm(new FromTerm(new InternetAddress("black_listed_domain.com")));

        SubjectTerm subjectTerm = new SubjectTerm("Notable");
        OrTerm orTerm = new OrTerm(fromTerm, new OrTerm(andTerm, subjectTerm));
        AndTerm andTerm1 = new AndTerm(orTerm, notFromTerm);
        /**
         * (FROM_pritomkucse@gmail.com OR (NOT_REED AND YESTERDAY) OR SUBJECT_CONTAINS_Notable) AND NOT_FROM_*@black_listed_domain.com
         */

        /* Custom search term, actually download email from server then check (slow) */
        SearchTerm searchTerm = new SearchTerm() {
            @Override
            public boolean match(Message message) {
                try {
                    if (message.getSubject().contains("forwarding")) {
                        return true;
                    }
                }
                catch (MessagingException ex) {
                    ex.printStackTrace();
                }
                return false;
            }
        };

        return andTerm1;
    }

    private static String saveFileFromEmailAttachment(Map attachment) {
        try {
            File dir = createAndGetDirectory();
            String fileName = attachment.get("fileName").toString();
            File toFile = new File(dir, fileName);
            MimeBodyPart mimeBodyPart = (MimeBodyPart) attachment.get("mimeBodyPart");
            mimeBodyPart.saveFile(toFile);
            return toFile.getAbsolutePath();
        }
        catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    private static File createAndGetDirectory() {
        File file = new File("attachments");
        if (!file.exists()) {
            file.mkdir();
        }
        return file;
    }

    private static Map processMultipart(Multipart multipart) throws Exception {
        Map output = new HashMap();
        output.put("html", "");
        output.put("text", "");
        List attachments = new ArrayList();

        for(int i = 0; i < multipart.getCount(); i++) {
            Map result = processBodyPart(multipart.getBodyPart(i));
            if (result != null) {
                if (result.containsKey("type")) {
                    if (result.get("type").toString().equalsIgnoreCase("html")) {
                        output.put("html", result.get("content").toString());
                    }
                    else if (result.get("type").toString().equalsIgnoreCase("text")) {
                        output.put("text", result.get("content").toString());
                    }
                    else if (result.get("type").toString().equalsIgnoreCase("attachment")) {
                        attachments.add(result);
                    }
                }
                if (result.containsKey("html")) {
                    output.put("html", result.get("html").toString());
                }
                if (result.containsKey("text")) {
                    output.put("text", result.get("text").toString());
                }
                if (result.containsKey("attachments")) {
                    List thisAttachments = (List) result.get("attachments");
                    for (int i2 = 0; i2 < thisAttachments.size(); i2++) {
                        attachments.add(thisAttachments.get(i2));
                    }
                }
            }
        }
        output.put("attachments", attachments);

        return output;
    }

    private static Map processBodyPart(BodyPart bodyPart) throws Exception {
        if(bodyPart.isMimeType("text/html") && bodyPart.getFileName() == null) {
            Map data = new HashMap();
            data.put("type", "html");
            data.put("content", bodyPart.getContent().toString());
            return data;
        }
        else if(bodyPart.isMimeType("text/plain") && bodyPart.getFileName() == null) {
            Map data = new HashMap();
            data.put("type", "text");
            data.put("content", bodyPart.getContent().toString());
            return data;
        }
        else if(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && bodyPart.getFileName() != null) {
            try {
                Map map = new HashMap();
                map.put("type", "attachment");
                map.put("fileName", bodyPart.getFileName());
                String fileType = bodyPart.getContentType();
                map.put("fileType", fileType.contains(":") ? fileType.substring(0, fileType.indexOf(";")) : fileType);
                map.put("mimeBodyPart", bodyPart);
                return map;
            }
            catch (Exception ex) {
                println("Error_Content=" + bodyPart.getContentType());
                ex.printStackTrace();
            }
        }
        else if(bodyPart.getContentType().contains("multipart")) {
            Map o = processMultipart((Multipart) bodyPart.getContent());
            return o;
        }
        return null;
    }

    private static String toSingleLine(String str) throws Exception {
        return str.replaceAll("\\s+", " ");
    }

    private static void println(Object o) {
        System.out.println(o);
    }
}