Example usage for org.apache.commons.mail HtmlEmail HtmlEmail

List of usage examples for org.apache.commons.mail HtmlEmail HtmlEmail

Introduction

In this page you can find the example usage for org.apache.commons.mail HtmlEmail HtmlEmail.

Prototype

HtmlEmail

Source Link

Usage

From source file:com.aurel.track.util.emailHandling.MailSender.java

/**
 * /*from  w  ww  .ja  v  a 2s  .  c  om*/
 * @param smtpMailSettings
 * @param internetAddressFrom
 * @param internetAddressesTo
 * @param subject
 * @param messageBody
 * @param isPlain
 * @param attachments
 * @param internetAddressesCC
 * @param internetAddressesBCC
 * @param internetAddressesReplayTo
 */
private void init(SMTPMailSettings smtpMailSettings, InternetAddress internetAddressFrom,
        InternetAddress[] internetAddressesTo, String subject, String messageBody, boolean isPlain,
        List<LabelValueBean> attachments, InternetAddress[] internetAddressesCC,
        InternetAddress[] internetAddressesBCC, InternetAddress[] internetAddressesReplayTo) {
    this.smtpMailSettings = smtpMailSettings;
    try {
        if (isPlain) {
            email = new SimpleEmail();
            if (attachments != null && attachments.size() > 0) {
                email = new MultiPartEmail();
            }
        } else {
            email = new HtmlEmail();
        }
        if (LOGGER.isTraceEnabled()) {
            email.setDebug(true);
        }
        email.setHostName(smtpMailSettings.getHost());
        email.setSmtpPort(smtpMailSettings.getPort());
        email.setCharset(smtpMailSettings.getMailEncoding() != null ? smtpMailSettings.getMailEncoding()
                : DEFAULTENCODINGT);
        if (timeout != null) {
            email.setSocketConnectionTimeout(timeout);
            email.setSocketTimeout(timeout);
        }
        if (smtpMailSettings.isReqAuth()) {
            email = setAuthMode(email);
        }
        email = setSecurityMode(email);

        for (int i = 0; i < internetAddressesTo.length; ++i) {
            email.addTo(internetAddressesTo[i].getAddress(), internetAddressesTo[i].getPersonal());
        }
        if (internetAddressesCC != null) {
            for (int i = 0; i < internetAddressesCC.length; ++i) {
                email.addCc(internetAddressesCC[i].getAddress(), internetAddressesCC[i].getPersonal());
            }
        }
        if (internetAddressesBCC != null) {
            for (int i = 0; i < internetAddressesBCC.length; ++i) {
                email.addBcc(internetAddressesBCC[i].getAddress(), internetAddressesBCC[i].getPersonal());
            }
        }
        if (internetAddressesReplayTo != null) {
            for (int i = 0; i < internetAddressesReplayTo.length; ++i) {
                email.addReplyTo(internetAddressesReplayTo[i].getAddress(),
                        internetAddressesReplayTo[i].getPersonal());
            }
        }
        email.setFrom(internetAddressFrom.getAddress(), internetAddressFrom.getPersonal());
        email.setSubject(subject);
        String cid = null;
        if (isPlain) {
            email.setMsg(messageBody);
        } else {
            if (messageBody.contains("cid:$$CID$$")) {
                URL imageURL = null;
                InputStream in = null;
                in = MailSender.class.getClassLoader().getResourceAsStream("tracklogo.gif");

                if (in != null) {
                    imageURL = new URL(ApplicationBean.getInstance().getServletContext().getResource("/")
                            + "logoAction.action?type=m");
                    DataSource ds = new ByteArrayDataSource(in, "image/" + "gif");
                    cid = ((HtmlEmail) email).embed(ds, "Genji");
                } else {
                    String theResource = "/WEB-INF/classes/resources/MailTemplates/tracklogo.gif";
                    imageURL = ApplicationBean.getInstance().getServletContext().getResource(theResource);
                    cid = ((HtmlEmail) email).embed(imageURL, "Genji");
                }
                messageBody = messageBody.replaceFirst("\\$\\$CID\\$\\$", cid);
            }
            Set<String> attachSet = new HashSet<String>();
            messageBody = MailImageBL.replaceInlineImages(messageBody, attachSet);
            if (!attachSet.isEmpty()) {
                Iterator<String> it = attachSet.iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    StringTokenizer st = new StringTokenizer(key, "_");
                    String workItemIDStr = st.nextToken();
                    String attachmentKeyStr = st.nextToken();
                    TAttachmentBean attachmentBean = null;
                    try {
                        attachmentBean = AttachBL.loadAttachment(Integer.valueOf(attachmentKeyStr),
                                Integer.valueOf(workItemIDStr), true);
                    } catch (Exception ex) {
                    }
                    if (attachmentBean != null) {
                        String fileName = attachmentBean.getFullFileNameOnDisk();
                        File file = new File(fileName);
                        InputStream is = new FileInputStream(file);
                        DataSource ds = new ByteArrayDataSource(is, "image/" + "gif");
                        cid = ((HtmlEmail) email).embed(ds, key);
                        messageBody = messageBody.replaceAll("cid:" + key, "cid:" + cid);
                    }
                }
            }
            ((HtmlEmail) email).setHtmlMsg(messageBody);
        }
        if (attachments != null && !attachments.isEmpty()) {
            includeAttachments(attachments);
        }
    } catch (Exception e) {
        LOGGER.error("Something went wrong trying to assemble an e-mail: " + e.getMessage());
    }

}

From source file:com.duroty.application.open.manager.OpenManager.java

/**
 * DOCUMENT ME!/*  w  w w  . j  a v  a  2  s. c  o  m*/
 *
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param from DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
private void sendData(Session msession, InternetAddress from, InternetAddress to, String username,
        String password, String signature) throws Exception {
    try {
        HtmlEmail email = new HtmlEmail();
        email.setMailSession(msession);

        email.setFrom(from.getAddress(), from.getPersonal());
        email.addTo(to.getAddress(), to.getPersonal());

        email.setSubject("Duroty System");
        email.setHtmlMsg("<p>Username: <b>" + username + "</b></p><p>Password: " + password + "<b></b></p><p>"
                + signature + "</p>");

        email.setCharset(MimeUtility.javaCharset(Charset.defaultCharset().displayName()));

        email.send();
    } finally {
    }
}

From source file:com.irurueta.server.commons.email.ApacheMailSender.java

/**
 * Method to send html email./*from   w  w w  .  ja v a 2 s. co  m*/
 * @param m email message to be sent.
 * @return id of message that has been sent.
 * @throws MailNotSentException if mail couldn't be sent.
 */
public String sendHtmlEmail(EmailMessage<HtmlEmail> m) throws MailNotSentException {
    try {
        HtmlEmail email = new HtmlEmail();
        internalSendApacheEmail(m, email);
    } catch (Throwable t) {
        throw new MailNotSentException(t);
    }
    return null;
}

From source file:com.ipc.service.SignUpService.java

public String sendhtmlmail(int uid, String key, String email) throws IOException, EmailException {
    HtmlEmail sendemail = new HtmlEmail();
    sendemail.setCharset("euc-kr");
    sendemail.setHostName("smtp.worksmobile.com");
    sendemail.addTo(email);/*w w  w.java  2  s.  c o  m*/
    sendemail.setFrom("jinuk@ideaconcert.com", "");
    sendemail.setSubject("?  ?? ?.");
    sendemail.setAuthentication("jinuk@ideaconcert.com", "tpxmapsb1");
    sendemail.setSmtpPort(465);
    sendemail.setSSL(true); //?
    sendemail.setTLS(true);
    sendemail.setDebug(true);
    String htmlmsg = "<html><div style='width:1000px; float:left; border-bottom:2px solid #45d4fe; padding-bottom:5px;box-sizing:border-box;'></div><div style='width:1000px;float:left; box-sizing:border-box; padding:15px;'><h2>? ?  ? .</h2><div style='width:100%; float:left; box-sizing:border-box; border:5px solid #f9f9f9; text-align:center; padding:40px 0 40px 0;'><span>   ? .</span><br><a href='http://localhost:8088/signup/permit?uid="
            + uid + "&key=" + key
            + "'><button style='width:150px; height:40px; background:none; border:2px solid #45d4fe; font-size:1.1rem; text-decoration: none;font-weight:bold; margin-top:10px;'></button></a></div></div></html>";
    System.out.println(htmlmsg);
    sendemail.setHtmlMsg(htmlmsg);
    try {
        sendemail.send();
    } catch (Exception e) {
        System.out.println("NOTOK");
        return "NOTOK";
    }
    return "OK";
}

From source file:br.com.mysqlmonitor.monitor.Monitor.java

private void enviarEmailDBA() {
    try {//from   www. ja  va 2  s  .com
        if (logs.length() != 0) {
            System.out.println("Divergencias: " + logs);
            for (Usuario usuario : usuarioDAO.findAll()) {
                System.out.println("Enviando email para: " + usuario.getNome());
                HtmlEmail email = new HtmlEmail();
                email.setHostName("smtp.googlemail.com");
                email.setSmtpPort(465);
                email.setAuthenticator(new DefaultAuthenticator("mysqlmonitorsuporte", "4rgvr6RM"));
                email.setSSL(true);
                email.setFrom("mysqlmonitorsuporte@gmail.com");
                email.setSubject("Log Mysql Monitor");
                email.setHtmlMsg(logs.toString());
                email.addTo(usuario.getEmail());
                email.send();
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.duroty.application.open.manager.OpenManager.java

/**
 * DOCUMENT ME!/*from  ww  w. j a v a 2 s  .  c o  m*/
 *
 * @param msession DOCUMENT ME!
 * @param from DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param username DOCUMENT ME!
 * @param password DOCUMENT ME!
 * @param signature DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 */
private void notifyToAdmins(Session msession, InternetAddress from, InternetAddress[] to, String user)
        throws Exception {
    try {
        HtmlEmail email = new HtmlEmail();
        email.setMailSession(msession);

        email.setFrom(from.getAddress(), from.getPersonal());

        HashSet aux = new HashSet(to.length);
        Collections.addAll(aux, to);
        email.setTo(aux);

        email.setSubject("User register in Duroty System");
        email.setHtmlMsg(
                "<p>The user solicits register into the system</p><p>The user is: <b>" + user + "</b></p>");

        email.setCharset(MimeUtility.javaCharset(Charset.defaultCharset().displayName()));

        email.send();
    } finally {
    }
}

From source file:com.ipc.service.SignUpService.java

public String sendpwmail(int uid, String key, String email) throws IOException, EmailException {
    System.out.println("Email : " + email);
    HtmlEmail sendemail = new HtmlEmail();
    sendemail.setCharset("euc-kr");
    sendemail.setHostName("smtp.worksmobile.com");
    sendemail.addTo(email);//from  www.j  a v a 2  s  .c om
    sendemail.setFrom("jinuk@ideaconcert.com", "");
    sendemail.setSubject("?  .");
    sendemail.setAuthentication("jinuk@ideaconcert.com", "tpxmapsb1");
    sendemail.setSmtpPort(465);
    sendemail.setSSL(true); //?
    sendemail.setTLS(true);
    sendemail.setDebug(true);
    String htmlmsg = "<html><div style='width:1000px; float:left; border-bottom:2px solid #45d4fe; padding-bottom:5px;box-sizing:border-box;'></div><div style='width:1000px;float:left; box-sizing:border-box; padding:15px;'><h2>?   .</h2><div style='width:100%; float:left; box-sizing:border-box; border:5px solid #f9f9f9; text-align:center; padding:40px 0 40px 0;'><span>  ?  <br> .<br>"
            + key + "</span></html>";
    System.out.println(htmlmsg);
    sendemail.setHtmlMsg(htmlmsg);
    try {
        sendemail.send();
    } catch (Exception e) {
        System.out.println("NOTOK");
        return "NOTOK";
    }
    return "OK";
}

From source file:com.googlecode.fascinator.messaging.EmailNotificationConsumer.java

private void sendEmails(List<String> toList, List<String> ccList, String subject, String body,
        String fromAddress, String fromName, boolean isHtml) throws EmailException {
    Email email = null;/*from ww  w  . ja v  a2  s.c  om*/
    if (isHtml) {
        email = new HtmlEmail();
        ((HtmlEmail) email).setHtmlMsg(body);
    } else {
        email = new SimpleEmail();
        email.setMsg(body);
    }
    email.setDebug(debug);
    email.setHostName(smtpHost);
    if (smtpUsername != null || smtpPassword != null) {
        email.setAuthentication(smtpUsername, smtpPassword);
    }
    email.setSmtpPort(smtpPort);
    email.setSslSmtpPort(smtpSslPort);
    email.setSSL(smtpSsl);
    email.setTLS(smtpTls);
    email.setSubject(subject);

    for (String to : toList) {
        email.addTo(to);
    }
    if (ccList != null) {
        for (String cc : ccList) {
            email.addCc(cc);
        }
    }
    email.setFrom(fromAddress, fromName);
    email.send();
}

From source file:com.delpac.bean.OrdenRetiroBean.java

public void enviarMail() throws EmailException, SQLException, IOException {
    StringBuilder sb = new StringBuilder();
    MultiPartEmail email = new HtmlEmail();
    try {//from  ww w.ja va2  s.  c o  m
        EmailAttachment attachment = new EmailAttachment();
        String exportDir = System.getProperty("catalina.base") + "/OrdenesRetiro/";
        String nom_archivo = "Orden_de_Retiro" + ord.getCod_ordenretiro() + ".pdf";
        attachment.setPath(exportDir + nom_archivo);
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription("Orden de retiro");
        attachment.setName(nom_archivo);
        //Mail
        String authuser = "Customerservice@delpac-sa.com";//LosInkas
        String authpwd = "cs6609";//LosInkas
        //            String authuser = "jorge.castaneda@bottago.com";
        //            String authpwd = "jorgec012";
        //            String authuser = "jorgito14@gmail.com";
        //            String authpwd = "p4s4j3r0";
        email.setSmtpPort(587);
        email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));
        email.setSSLOnConnect(false); //LosInkas
        //            email.setSSLOnConnect(true); //Gmail
        email.setDebug(true);
        email.setHostName("mailserver.losinkas.com"); //LosInkas
        //            email.setHostName("ns0.ovh.net");
        //            email.setHostName("smtp.gmail.com");
        email.getMailSession().getProperties().put("mail.smtps.auth", "false");
        email.getMailSession().getProperties().put("mail.debug", "true");
        email.getMailSession().getProperties().put("mail.smtp.port", "26"); //LosInkas
        //            email.getMailSession().getProperties().put("mail.smtp.port", "587");
        //            email.getMailSession().getProperties().put("mail.smtps.socketFactory.port", "587"); //gmail
        email.getMailSession().getProperties().put("mail.smtps.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory"); //gmail
        email.getMailSession().getProperties().put("mail.smtps.socketFactory.fallback", "false");
        email.getMailSession().getProperties().put("mail.smtp.ssl.enable", "false");
        email.setFrom("Customerservice@delpac-sa.com", "Servico al cliente Delpac");//LosInkas
        //            email.setFrom("jorgito14@gmail.com", "Prueba envo de correo");
        email.setSubject(ord.getCia_nombre() + " / " + ord.getPto_nombre() + "/ BOOKING " + ord.getBooking()
                + " " + ord.getDsp_itinerario());

        sb.append("<strong>Estimados:</strong><br />").append(System.lineSeparator());
        sb.append("Buenas, adjunto la orden de retiro para la nave <strong>" + ord.getDsp_itinerario()
                + "</strong><br />").append(System.lineSeparator());
        sb.append("<br />" + "<ul><li>Favor retirar el sello en nuestras oficinas.</li>"
                + "<li><strong>Traer la orden de retiro</strong> para poder formalizar la entrega del sello.</li>"
                + "<li><strong>Copia de cedula</strong> de la persona que retirar el sello.</li>"
                + "<li><strong>Traer carta de autorizacin</strong> por parte del exportador nombrando al delegado que retirar el sello.</li>"
                + "<li><strong>MUY IMPORTANTE: Se recuerda que a partir del 1 de Julio, 2016 todo contenedor deber contar con certificado de "
                + "VGM (Masa Bruta Verificada) antes del embarque, caso contrario el contenedor no podr ser considerado para embarque. CUT OFF VGM, "
                + "24 horas antes del atraque de la nave.</strong></li> " + "<br /><br />")
                .append(System.lineSeparator());
        sb.append("Seores de <strong>" + ord.getLoc_salidades() + "</strong> favor " + ord.getCondicion()
                + "<br /><br />").append(System.lineSeparator());
        if (!ord.getDetalle().isEmpty()) {
            sb.append(ord.getDetalle()).append(System.lineSeparator());
            sb.append(
                    "<br /><strong>Requerimiento Especial: " + ord.getReq_especial2() + "</strong><br /><br />")
                    .append(System.lineSeparator());
            sb.append("<strong>Remark:</strong> " + ord.getRemark() + " <br /><br />")
                    .append(System.lineSeparator());
            sb.append("Gracias.<br /><br />" + "<strong>Saludos Cordiales / Best Regards</strong><br />"
                    + "JOSE CARRIEL M. II DELPAC S.A. II Av. 9 de Octubre 2009 y Los Ros, Edificio el Marqus II Guayaquil - Ecuador <br />"
                    + "Tel.: +593 42371 172/ +593 42365 626 II Cel.: +59 998152266 II Mail: jcarriel@delpac-sa.com");
        } else {
            sb.append(
                    "<br /><strong>Requerimiento Especial: " + ord.getReq_especial2() + "</strong><br /><br />")
                    .append(System.lineSeparator());
            sb.append("<strong>Remark:</strong> " + ord.getRemark() + " <br /><br />")
                    .append(System.lineSeparator());
            sb.append("Gracias.<br /><br />" + "<strong>Saludos Cordiales / Best Regards</strong><br />"
                    + "JOSE CARRIEL M. II DELPAC S.A. II Av. 9 de Octubre 2009 y Los Ros, Edificio el Marqus II Guayaquil - Ecuador <br />"
                    + "Tel.: +593 42371 172/ +593 42365 626 II Cel.: +59 998152266 II Mail: jcarriel@delpac-sa.com");
            email.setMsg(sb.toString());
        }
        email.setMsg(sb.toString());
        email.addTo(ord.getDestinario().split(","));
        //email.addTo("gint1@tercon.com.ec, gout2@tercon.com.ec, controlgate@tercon.com.ec, " + ord.getDestinario().split(",")); //LosInkas
        if (!ord.getCc().isEmpty()) {
            //email.addCc("dgonzalez@delpac-sa.com, charmsen@delpac-sa.com, vmendoza@delpac-sa.com, vzambrano@delpac-sa.com, vchiriboga@delpac-sa.com, vortiz@delpac-sa.com, mbenitez@delpac-sa.com, crobalino@delpac-sa.com, jcarriel@delpac-sa.com, fsalame@delpac-sa.com," + ord.getCc().split(",")); //LosInkas
            email.addCc("jorge_3_11_91@hotmail," + ord.getCc().split(",")); //LosInkas
        } else {
            //                email.addCc("dgonzalez@delpac-sa.com, charmsen@delpac-sa.com, vmendoza@delpac-sa.com, vzambrano@delpac-sa.com, vchiriboga@delpac-sa.com, vortiz@delpac-sa.com, mbenitez@delpac-sa.com, crobalino@delpac-sa.com, jcarriel@delpac-sa.com, fsalame@delpac-sa.com"); //LosInkas
            email.addCc("jorge_3_11_91@hotmail.com"); //LosInkas
        }

        //Add attach
        email.attach(attachment);

        //Send mail
        email.send();
        daoOrdenRetiro.updateVerificaPDF(ord, ord.getCod_ordenretiro());
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage("",
                new FacesMessage(FacesMessage.SEVERITY_INFO, "Atencin", "El mail ha sido enviado"));
    } catch (EmailException ee) {
        ee.printStackTrace();
    }
}

From source file:com.duroty.application.mail.manager.SendManager.java

/**
 * DOCUMENT ME!/*from  w  w w  . j a va 2 s  . c o  m*/
 *
 * @param hsession DOCUMENT ME!
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param ideIdint DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param cc DOCUMENT ME!
 * @param bcc DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 * @param attachments DOCUMENT ME!
 * @param isHtml DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param headers DOCUMENT ME!
 * @param priority DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void saveDraft(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint,
        String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml,
        String charset, InternetHeaders headers, String priority) throws MailException {
    try {
        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        if ((body == null) || body.trim().equals("")) {
            body = " ";
        }

        Email email = null;

        if (isHtml) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(charset);

        Users user = getUser(hsession, repositoryName);
        Identity identity = getIdentity(hsession, ideIdint, user);

        InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName());
        InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null);
        InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null);
        InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null);

        if (_from != null) {
            email.setFrom(_from.getAddress(), _from.getPersonal());
        }

        if (_returnPath != null) {
            email.addHeader("Return-Path", _returnPath.getAddress());
            email.addHeader("Errors-To", _returnPath.getAddress());
            email.addHeader("X-Errors-To", _returnPath.getAddress());
        }

        if (_replyTo != null) {
            email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
        }

        if ((_to != null) && (_to.length > 0)) {
            HashSet aux = new HashSet(_to.length);
            Collections.addAll(aux, _to);
            email.setTo(aux);
        }

        if ((_cc != null) && (_cc.length > 0)) {
            HashSet aux = new HashSet(_cc.length);
            Collections.addAll(aux, _cc);
            email.setCc(aux);
        }

        if ((_bcc != null) && (_bcc.length > 0)) {
            HashSet aux = new HashSet(_bcc.length);
            Collections.addAll(aux, _bcc);
            email.setBcc(aux);
        }

        email.setSubject(subject);

        Date now = new Date();

        email.setSentDate(now);

        File dir = new File(System.getProperty("user.home") + File.separator + "tmp");
        if (!dir.exists()) {
            dir.mkdir();
        }

        if ((attachments != null) && (attachments.size() > 0)) {
            for (int i = 0; i < attachments.size(); i++) {
                ByteArrayInputStream bais = null;
                FileOutputStream fos = null;

                try {
                    MailPartObj obj = (MailPartObj) attachments.get(i);

                    File file = new File(dir, obj.getName());

                    bais = new ByteArrayInputStream(obj.getAttachent());
                    fos = new FileOutputStream(file);
                    IOUtils.copy(bais, fos);

                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(file.getPath());
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    attachment.setDescription("File Attachment: " + file.getName());
                    attachment.setName(file.getName());

                    if (email instanceof MultiPartEmail) {
                        ((MultiPartEmail) email).attach(attachment);
                    }
                } catch (Exception ex) {

                } finally {
                    IOUtils.closeQuietly(bais);
                    IOUtils.closeQuietly(fos);
                }
            }
        }

        if (headers != null) {
            Header xheader;
            Enumeration xe = headers.getAllHeaders();

            for (; xe.hasMoreElements();) {
                xheader = (Header) xe.nextElement();

                if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                }
            }
        }

        if (priority != null) {
            if (priority.equals("high")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "1");
            } else if (priority.equals("low")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "5");
            }
        }

        if (email instanceof HtmlEmail) {
            ((HtmlEmail) email).setHtmlMsg(body);
        } else {
            email.setMsg(body);
        }

        email.setMailSession(session);

        email.buildMimeMessage();

        MimeMessage mime = email.getMimeMessage();
        int size = MessageUtilities.getMessageSize(mime);

        if (!controlQuota(hsession, user, size)) {
            throw new MailException("ErrorMessages.mail.quota.exceded");
        }

        messageable.storeDraftMessage(getId(), mime, user);
    } catch (MailException e) {
        throw e;
    } catch (Exception e) {
        throw new MailException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new MailException(ex);
    } catch (Throwable e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}