Example usage for javax.mail Session getDefaultInstance

List of usage examples for javax.mail Session getDefaultInstance

Introduction

In this page you can find the example usage for javax.mail Session getDefaultInstance.

Prototype

public static synchronized Session getDefaultInstance(Properties props, Authenticator authenticator) 

Source Link

Document

Get the default Session object.

Usage

From source file:contestWebsite.Registration.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity contestInfo = Retrieve.contestInfo();

    Map<String, String[]> params = new HashMap<String, String[]>(req.getParameterMap());
    for (Entry<String, String[]> param : params.entrySet()) {
        if (!"studentData".equals(param.getKey())) {
            params.put(param.getKey(), new String[] { escapeHtml4(param.getValue()[0]) });
        }/*from   w  w w . j a  va  2s . c  om*/
    }

    String registrationType = params.get("registrationType")[0];
    String account = "no";
    if (params.containsKey("account")) {
        account = "yes";
    }
    String email = params.containsKey("email") && params.get("email")[0].length() > 0
            ? params.get("email")[0].toLowerCase().trim()
            : null;
    String schoolLevel = params.get("schoolLevel")[0];
    String schoolName = params.get("schoolName")[0].trim();
    String name = params.get("name")[0].trim();
    String classification = params.containsKey("classification") ? params.get("classification")[0] : "";
    String studentData = req.getParameter("studentData");
    String password = null;
    String confPassword = null;

    UserCookie userCookie = UserCookie.getCookie(req);
    boolean loggedIn = userCookie != null && userCookie.authenticate();
    if ((!loggedIn || !userCookie.isAdmin()) && email == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "E-Mail Address parameter ('email') must be specified");
        return;
    }

    HttpSession sess = req.getSession(true);
    sess.setAttribute("registrationType", registrationType);
    sess.setAttribute("account", account);
    sess.setAttribute("account", account);
    sess.setAttribute("name", name);
    sess.setAttribute("classification", classification);
    sess.setAttribute("schoolName", schoolName);
    sess.setAttribute("schoolLevel", schoolLevel);
    sess.setAttribute("email", email);
    sess.setAttribute("studentData", studentData);

    boolean reCaptchaResponse = false;
    if (!(Boolean) sess.getAttribute("nocaptcha")) {
        URL reCaptchaURL = new URL("https://www.google.com/recaptcha/api/siteverify");
        String charset = java.nio.charset.StandardCharsets.UTF_8.name();
        String reCaptchaQuery = String.format("secret=%s&response=%s&remoteip=%s",
                URLEncoder.encode((String) contestInfo.getProperty("privateKey"), charset),
                URLEncoder.encode(req.getParameter("g-recaptcha-response"), charset),
                URLEncoder.encode(req.getRemoteAddr(), charset));

        final URLConnection connection = new URL(reCaptchaURL + "?" + reCaptchaQuery).openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        String response = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
            @Override
            public InputStream getInput() throws IOException {
                return connection.getInputStream();
            }
        }, Charsets.UTF_8));

        try {
            JSONObject JSONResponse = new JSONObject(response);
            reCaptchaResponse = JSONResponse.getBoolean("success");
        } catch (JSONException e) {
            e.printStackTrace();
            resp.sendRedirect("/contactUs?captchaError=1");
            return;
        }
    }

    if (!(Boolean) sess.getAttribute("nocaptcha") && !reCaptchaResponse) {
        resp.sendRedirect("/registration?captchaError=1");
    } else {
        if (account.equals("yes")) {
            password = params.get("password")[0];
            confPassword = params.get("confPassword")[0];
        }

        Query query = new Query("registration")
                .setFilter(new FilterPredicate("email", FilterOperator.EQUAL, email)).setKeysOnly();
        List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1));

        if (users.size() != 0 && email != null || account.equals("yes") && !confPassword.equals(password)) {
            if (users.size() != 0) {
                resp.sendRedirect("/registration?userError=1");
            } else if (!params.get("confPassword")[0].equals(params.get("password")[0])) {
                resp.sendRedirect("/registration?passwordError=1");
            } else {
                resp.sendRedirect("/registration?updated=1");
            }
        } else {
            Entity registration = new Entity("registration");
            registration.setProperty("registrationType", registrationType);
            registration.setProperty("account", account);
            registration.setProperty("schoolName", schoolName);
            registration.setProperty("schoolLevel", schoolLevel);
            registration.setProperty("name", name);
            registration.setProperty("classification", classification);
            registration.setProperty("studentData", new Text(studentData));
            registration.setProperty("email", email);
            registration.setProperty("paid", "");
            registration.setProperty("timestamp", new Date());

            JSONArray regData = null;
            try {
                regData = new JSONArray(studentData);
            } catch (JSONException e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                return;
            }

            long price = (Long) contestInfo.getProperty("price");
            int cost = (int) (0 * price);

            for (int i = 0; i < regData.length(); i++) {
                try {
                    JSONObject studentRegData = regData.getJSONObject(i);
                    for (Subject subject : Subject.values()) {
                        cost += price * (studentRegData.getBoolean(subject.toString()) ? 1 : 0);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                    return;
                }
            }

            registration.setProperty("cost", cost);

            Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true));
            try {
                datastore.put(registration);

                if (account.equals("yes") && password != null && password.length() > 0 && email != null) {
                    Entity user = new Entity("user");
                    String hash = Password.getSaltedHash(password);
                    user.setProperty("name", name);
                    user.setProperty("school", schoolName);
                    user.setProperty("schoolLevel", schoolLevel);
                    user.setProperty("user-id", email);
                    user.setProperty("salt", hash.split("\\$")[0]);
                    user.setProperty("hash", hash.split("\\$")[1]);
                    datastore.put(user);
                }

                txn.commit();

                sess.setAttribute("props", registration.getProperties());

                if (email != null) {
                    Session session = Session.getDefaultInstance(new Properties(), null);
                    String appEngineEmail = (String) contestInfo.getProperty("account");

                    String url = req.getRequestURL().toString();
                    url = url.substring(0, url.indexOf("/", 7));

                    try {
                        Message msg = new MimeMessage(session);
                        msg.setFrom(new InternetAddress(appEngineEmail, "Tournament Website Admin"));
                        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, name));
                        msg.setSubject("Thank you for your registration!");

                        VelocityEngine ve = new VelocityEngine();
                        ve.init();

                        VelocityContext context = new VelocityContext();
                        context.put("name", name);
                        context.put("url", url);
                        context.put("cost", cost);
                        context.put("title", contestInfo.getProperty("title"));
                        context.put("account", account.equals("yes"));

                        StringWriter sw = new StringWriter();
                        Velocity.evaluate(context, sw, "registrationEmail",
                                ((Text) contestInfo.getProperty("registrationEmail")).getValue());
                        msg.setContent(sw.toString(), "text/html");
                        Transport.send(msg);
                    } catch (MessagingException e) {
                        e.printStackTrace();
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                        return;
                    }
                }

                resp.sendRedirect("/registration?updated=1");
            } catch (Exception e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            } finally {
                if (txn.isActive()) {
                    txn.rollback();
                }
            }
        }
    }
}

From source file:com.azprogrammer.qgf.controllers.HomeController.java

@RequestMapping(value = "/wbmail")
public ModelAndView doWhiteboardMail(ModelMap model, HttpServletRequest req) {
    model.clear();/*  www . j  a  v  a2s  . c  om*/

    try {
        WBEmail email = new WBEmail();
        HttpSession session = req.getSession();
        String userName = session.getAttribute("userName").toString();
        String toAddress = req.getParameter("email");

        if (!WebUtil.isValidEmail(toAddress)) {
            throw new Exception("invalid email");

        }

        //TODO validate message contents
        email.setFromUser(userName);
        email.setToAddress(toAddress);

        WhiteBoard wb = getWhiteBoard(req);
        if (wb == null) {
            throw new Exception("Invalid White Board");
        }

        email.setWbKey(wb.getKey());
        email.setCreationTime(System.currentTimeMillis());

        Properties props = new Properties();
        Session mailsession = Session.getDefaultInstance(props, null);

        String emailError = null;
        try {
            MimeMessage msg = new MimeMessage(mailsession);
            msg.setFrom(new InternetAddress("no_reply@drawitlive.com", "Draw it Live"));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
            msg.setSubject("Please join the whiteboard session on " + req.getServerName());
            String msgBody = "To join " + userName
                    + " on a colloborative whiteboard follow this link: <a href=\"http://" + req.getServerName()
                    + "/whiteboard/" + req.getParameter("wbId") + "\"> http://" + req.getServerName()
                    + "/whiteboard/" + req.getParameter("wbId") + "</a>";
            msg.setText(msgBody, "UTF-8", "html");
            Transport.send(msg);

        } catch (AddressException e) {
            emailError = e.getMessage();
        } catch (MessagingException e) {
            emailError = e.getMessage();
        }

        if (emailError == null) {
            email.setStatus(WBEmail.STATUS_SENT);
        } else {
            email.setStatus(WBEmail.STATUS_ERROR);
        }

        getPM().makePersistent(email);

        if (email.getStatus() == WBEmail.STATUS_ERROR) {
            throw new Exception(emailError);
        }

        model.put("status", "ok");

    } catch (Exception e) {
        model.put("error", e.getMessage());
    }

    return doJSON(model);
}

From source file:javamailclient.GmailAPI.java

public static MimeMessage getMimeMessage(String messageId) throws IOException, MessagingException {
    String userId = USER;/* ww  w  .  j  a  v  a  2 s  . c  om*/
    Message message = service.users().messages().get(userId, messageId).setFormat("raw").execute();

    byte[] emailBytes = Base64.decodeBase64(message.getRaw());

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(emailBytes));
    //System.out.println(email.getContentType());
    return email;
}

From source file:javamailclient.GmailAPI.java

public static Map getMessageDetails(String messageId) throws IOException, MessagingException {
    Map<String, String> mapDetails = new HashMap<String, String>();
    Message message = service.users().messages().get("me", messageId).setFormat("raw").execute();
    byte[] bytes = Base64.decodeBase64(message.getRaw());

    Properties prop = new Properties();
    Session session = Session.getDefaultInstance(prop, null);

    MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(bytes));
    mapDetails.put("subject", email.getSubject());
    String from = "None";
    if (email.getSender() != null) {
        from = email.getSender().toString();
    }/* w  ww.j  a  v  a2  s . com*/
    mapDetails.put("from", from);
    String date = "Unknown";
    if (email.getReceivedDate() != null) {
        date = email.getReceivedDate().toString();
    }
    mapDetails.put("receiveddate", date);
    date = "Unknown";
    if (email.getSentDate() != null) {
        date = email.getSentDate().toString();
    }
    mapDetails.put("senddate", date);
    mapDetails.put("body", getMessageBody(email));
    return mapDetails;
}

From source file:org.zilverline.core.IMAPCollection.java

/**
 * Sets existsOnDisk based on whether the collection (contentDir) actually (now) sits on disk.
 * /*from w  w w.jav a  2  s  . co  m*/
 * @todo the whole existsOnDisk construction is a little funny, refactor some time
 */
protected void setExistsOnDisk() {
    existsOnDisk = false;
    Store store = null;
    try {
        // try to connect to server and find folder
        log.debug("Connecting to IMAP server: " + host);
        Properties props = System.getProperties();
        Session session = Session.getDefaultInstance(props, null);
        store = session.getStore("imap");
        log.debug("Connecting to " + host + " as " + user);
        store.connect(host, user, password);
        log.debug("Connected");
        // start at the proper folder
        Folder topFolder = null;
        if (StringUtils.hasText(folder)) {
            topFolder = store.getFolder(folder);
        } else {
            topFolder = store.getDefaultFolder();
        }
        existsOnDisk = (topFolder != null);
    } catch (NoSuchProviderException e) {
        log.warn("Can't connect to " + host, e);
    } catch (MessagingException e) {
        log.warn("Error while accessing IMAP server " + host, e);
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e1) {
                log.error("Error closing IMAP server " + host, e1);
            }
        }
    }
}

From source file:org.protocoderrunner.apprunner.api.PNetwork.java

@ProtocoderScript
@APIMethod(description = "Send an E-mail. It requires passing a EmailConf object", example = "")
@APIParam(params = { "url", "function(data)" })
public void sendEmail(String from, String to, String subject, String text, final EmailConf emailSettings)
        throws AddressException, MessagingException {

    if (emailSettings == null) {
        return;//from   w  w  w . j a  v a  2s  . c  o m
    }

    // final String host = "smtp.gmail.com";
    // final String address = "@gmail.com";
    // final String pass = "";

    Multipart multiPart;
    String finalString = "";

    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", emailSettings.ttl);
    props.put("mail.smtp.host", emailSettings.host);
    props.put("mail.smtp.user", emailSettings.user);
    props.put("mail.smtp.password", emailSettings.password);
    props.put("mail.smtp.port", emailSettings.port);
    props.put("mail.smtp.auth", emailSettings.auth);

    Log.i("Check", "done pops");
    final Session session = Session.getDefaultInstance(props, null);
    DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain"));
    final MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setDataHandler(handler);
    Log.i("Check", "done sessions");

    multiPart = new MimeMultipart();

    InternetAddress toAddress;
    toAddress = new InternetAddress(to);
    message.addRecipient(Message.RecipientType.TO, toAddress);
    Log.i("Check", "added recipient");
    message.setSubject(subject);
    message.setContent(multiPart);
    message.setText(text);

    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                MLog.i("check", "transport");
                Transport transport = session.getTransport("smtp");
                MLog.i("check", "connecting");
                transport.connect(emailSettings.host, emailSettings.user, emailSettings.password);
                MLog.i("check", "wana send");
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();

                MLog.i("check", "sent");

            } catch (AddressException e) {
                e.printStackTrace();
            } catch (MessagingException e) {
                e.printStackTrace();
            }

        }
    });
    t.start();

}

From source file:com.enonic.vertical.userservices.OrderHandlerController.java

private void sendMail(String receiverEmail, String receiverName, String senderEmail, String senderName,
        String subject, String message) throws MessagingException, UnsupportedEncodingException {

    // smtp server
    Properties smtpProperties = new Properties();
    smtpProperties.put("mail.smtp.host", verticalProperties.getMailSmtpHost());
    Session session = Session.getDefaultInstance(smtpProperties, null);

    // create message
    Message msg = new MimeMessage(session);

    // set from address
    if (senderEmail != null && !senderEmail.equals("")) {
        InternetAddress addressFrom = new InternetAddress(senderEmail);
        if (senderName != null && !senderName.equals("")) {
            addressFrom.setPersonal(senderName);
        }/*from  w  w w .  j av  a 2 s .  c o m*/
        msg.setFrom(addressFrom);
    }

    // set to address
    InternetAddress addressTo = new InternetAddress(receiverEmail);
    if (receiverName != null) {
        addressTo.setPersonal(receiverName);
    }
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    // Setting subject and content type
    msg.setSubject(subject);

    message = RegexpUtil.substituteAll("(\\\\n)", "\n", message);
    msg.setContent(message, "text/plain; charset=UTF-8");

    // send message
    Transport.send(msg);
}

From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java

protected Store connectToStore() throws MessagingException {
    EmailConfig config = getConfig();/*from  w  w w  .j  ava 2  s.  c o m*/
    EmailProvider provider = getEmailProvider(config.getProviderId());
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", provider.getIncomingProto());

    Session session = Session.getDefaultInstance(props, null);

    Store store = session.getStore(provider.getIncomingProto());
    store.connect(provider.getIncomingServer(), provider.getIncomingPort(), config.getUsername(),
            config.getPassword());
    return store;
}

From source file:com.openkm.util.impexp.RepositoryImporter.java

/**
 * Import mail.//  w  w  w.  ja v  a  2  s.c  o  m
 */
private static ImpExpStats importMail(String token, String fldPath, String fileName, File fDoc,
        boolean metadata, Writer out, InfoDecorator deco) throws IOException, PathNotFoundException,
        AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException {
    FileInputStream fisContent = new FileInputStream(fDoc);
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    MailModule mm = ModuleManager.getMailModule();
    Properties props = System.getProperties();
    props.put("mail.host", "smtp.dummydomain.com");
    props.put("mail.transport.protocol", "smtp");
    ImpExpStats stats = new ImpExpStats();
    int size = fisContent.available();
    Mail mail = new Mail();
    Gson gson = new Gson();
    boolean api = false;

    try {
        // Metadata
        if (metadata) {
            // Read serialized document metadata
            File jsFile = new File(fDoc.getPath() + Config.EXPORT_METADATA_EXT);
            log.info("Document Metadata File: {}", jsFile.getPath());

            if (jsFile.exists() && jsFile.canRead()) {
                FileReader fr = new FileReader(jsFile);
                MailMetadata mmd = gson.fromJson(fr, MailMetadata.class);
                mail.setPath(fldPath + "/" + fileName);
                mmd.setPath(mail.getPath());
                IOUtils.closeQuietly(fr);
                log.info("Mail Metadata: {}", mmd);

                // Apply metadata
                ma.importWithMetadata(mmd);

                // Add attachments
                if (fileName.endsWith(".eml")) {
                    Session mailSession = Session.getDefaultInstance(props, null);
                    MimeMessage msg = new MimeMessage(mailSession, fisContent);
                    mail = MailUtils.messageToMail(msg);
                    mail.setPath(fldPath + "/" + mmd.getName());
                    MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());
                } else if (fileName.endsWith(".msg")) {
                    Message msg = new MsgParser().parseMsg(fisContent);
                    mail = MailUtils.messageToMail(msg);
                    mail.setPath(fldPath + "/" + mmd.getName());
                    MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());
                } else {
                    throw new MessagingException("Unknown mail format");
                }

                FileLogger.info(BASE_NAME, "Created document ''{0}''", mail.getPath());
                log.info("Created document '{}'", mail.getPath());
            } else {
                log.warn("Unable to read metadata file: {}", jsFile.getPath());
                api = true;
            }
        } else {
            api = true;
        }

        if (api) {
            if (fileName.endsWith(".eml")) {
                Session mailSession = Session.getDefaultInstance(props, null);
                MimeMessage msg = new MimeMessage(mailSession, fisContent);
                mail = MailUtils.messageToMail(msg);
                mail.setPath(fldPath + "/" + UUID.randomUUID().toString() + "-"
                        + PathUtils.escape(mail.getSubject()));
                mm.create(token, mail);
                MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());
            } else if (fileName.endsWith(".msg")) {
                Message msg = new MsgParser().parseMsg(fisContent);
                mail = MailUtils.messageToMail(msg);
                mail.setPath(fldPath + "/" + UUID.randomUUID().toString() + "-"
                        + PathUtils.escape(mail.getSubject()));
                mm.create(token, mail);
                MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());
            } else {
                throw new MessagingException("Unknown mail format");
            }

            FileLogger.info(BASE_NAME, "Created mail ''{0}''", mail.getPath());
            log.info("Created mail ''{}''", mail.getPath());
        }

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), null));
            out.flush();
        }

        // Stats
        stats.setSize(stats.getSize() + size);
        stats.setMails(stats.getMails() + 1);
    } catch (UnsupportedMimeTypeException e) {
        log.warn("UnsupportedMimeTypeException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UnsupportedMimeType"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UnsupportedMimeTypeException ''{0}''", mail.getPath());
    } catch (FileSizeExceededException e) {
        log.warn("FileSizeExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "FileSizeExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "FileSizeExceededException ''{0}''", mail.getPath());
    } catch (UserQuotaExceededException e) {
        log.warn("UserQuotaExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UserQuotaExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UserQuotaExceededException ''{0}''", mail.getPath());
    } catch (VirusDetectedException e) {
        log.warn("VirusWarningException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "VirusWarningException"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "VirusWarningException ''{0}''", mail.getPath());
    } catch (ItemExistsException e) {
        log.warn("ItemExistsException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "ItemExists"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", mail.getPath());
    } catch (JsonParseException e) {
        log.warn("JsonParseException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", mail.getPath());
    } catch (MessagingException e) {
        log.warn("MessagingException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Messaging"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "MessagingException ''{0}''", mail.getPath());
    } catch (Exception e) {
        log.warn("Exception: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "General"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "Exception ''{0}''", mail.getPath());
    } finally {
        IOUtils.closeQuietly(fisContent);
    }

    return stats;
}

From source file:com.ikon.util.impexp.RepositoryImporter.java

/**
 * Import mail.// ww w.j  a  v  a2  s.c om
 */
private static ImpExpStats importMail(String token, File fs, String fldPath, String fileName, File fDoc,
        String metadata, Writer out, InfoDecorator deco) throws IOException, PathNotFoundException,
        AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException {
    FileInputStream fisContent = new FileInputStream(fDoc);
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    MailModule mm = ModuleManager.getMailModule();
    Properties props = System.getProperties();
    props.put("mail.host", "smtp.dummydomain.com");
    props.put("mail.transport.protocol", "smtp");
    ImpExpStats stats = new ImpExpStats();
    int size = fisContent.available();
    Mail mail = new Mail();
    Gson gson = new Gson();
    boolean api = false;

    try {
        // Metadata
        if (metadata.equals("JSON")) {
            // Read serialized document metadata
            File jsFile = new File(fDoc.getPath() + Config.EXPORT_METADATA_EXT);
            log.info("Document Metadata File: {}", jsFile.getPath());

            if (jsFile.exists() && jsFile.canRead()) {
                FileReader fr = new FileReader(jsFile);
                MailMetadata mmd = gson.fromJson(fr, MailMetadata.class);
                mail.setPath(fldPath + "/" + fileName);
                mmd.setPath(mail.getPath());
                IOUtils.closeQuietly(fr);
                log.info("Mail Metadata: {}", mmd);

                // Apply metadata
                ma.importWithMetadata(mmd);

                // Add attachments
                Session mailSession = Session.getDefaultInstance(props, null);
                MimeMessage msg = new MimeMessage(mailSession, fisContent);
                mail = MailUtils.messageToMail(msg);
                mail.setPath(fldPath + "/" + mmd.getName());
                MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());

                FileLogger.info(BASE_NAME, "Created document ''{0}''", mail.getPath());
                log.info("Created document '{}'", mail.getPath());
            } else {
                log.warn("Unable to read metadata file: {}", jsFile.getPath());
                api = true;
            }
        } else {
            api = true;
        }

        if (api) {
            Session mailSession = Session.getDefaultInstance(props, null);
            MimeMessage msg = new MimeMessage(mailSession, fisContent);
            mail = MailUtils.messageToMail(msg);
            mail.setPath(fldPath + "/" + fileName);
            mm.create(token, mail);
            MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());

            FileLogger.info(BASE_NAME, "Created mail ''{0}''", mail.getPath());
            log.info("Created mail ''{}''", mail.getPath());
        }

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), null));
            out.flush();
        }

        // Stats
        stats.setSize(stats.getSize() + size);
        stats.setMails(stats.getMails() + 1);
    } catch (UnsupportedMimeTypeException e) {
        log.warn("UnsupportedMimeTypeException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UnsupportedMimeType"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UnsupportedMimeTypeException ''{0}''", mail.getPath());
    } catch (FileSizeExceededException e) {
        log.warn("FileSizeExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "FileSizeExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "FileSizeExceededException ''{0}''", mail.getPath());
    } catch (UserQuotaExceededException e) {
        log.warn("UserQuotaExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UserQuotaExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UserQuotaExceededException ''{0}''", mail.getPath());
    } catch (VirusDetectedException e) {
        log.warn("VirusWarningException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "VirusWarningException"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "VirusWarningException ''{0}''", mail.getPath());
    } catch (ItemExistsException e) {
        log.warn("ItemExistsException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "ItemExists"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", mail.getPath());
    } catch (JsonParseException e) {
        log.warn("JsonParseException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", mail.getPath());
    } catch (MessagingException e) {
        log.warn("MessagingException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "MessagingException ''{0}''", mail.getPath());
    } finally {
        IOUtils.closeQuietly(fisContent);
    }

    return stats;
}