Example usage for org.apache.commons.mail MultiPartEmail addCc

List of usage examples for org.apache.commons.mail MultiPartEmail addCc

Introduction

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

Prototype

public Email addCc(final String email) throws EmailException 

Source Link

Document

Add a recipient CC to the email.

Usage

From source file:com.maxl.java.amikodesk.Emailer.java

public void send() {
    try {/*  w w  w . j a  va 2 s .  c om*/
        MultiPartEmail email = new MultiPartEmail();
        email.setHostName(m_es);
        email.setSmtpPort(465);
        email.setAuthenticator(new DefaultAuthenticator(m_el, m_ep));
        email.setSSLOnConnect(true);

        // Create email message
        email.setSubject(m_subject); // Subject         
        email.setMsg(m_body); // Body
        email.setFrom(m_from); // From field      
        email.addTo(m_recipient); // Recipient   
        if (m_singlecc != null && !m_singlecc.isEmpty())
            email.addCc(m_singlecc); // CC
        if (m_replyTo != null && !m_replyTo.isEmpty())
            email.addReplyTo(m_replyTo); // Reply-To
        // Add attachments
        for (Map.Entry<String, String> entry : m_map_of_attachments.entrySet()) {
            EmailAttachment attachment = new EmailAttachment();
            attachment.setName(entry.getKey());
            attachment.setPath(entry.getValue());
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            email.attach(attachment);
        }

        // Send email
        email.send();

        // Clear map
        m_map_of_attachments.clear();
    } catch (EmailException e) {
        e.printStackTrace();
    }
}

From source file:com.dominion.salud.pedicom.negocio.tools.MAILService.java

/**
 * configura el ciente de correo y envia el correo con un adjunto
 *
 * @param to//from www . ja  v  a 2 s  . c  o m
 * @param attach el archivo que se adjunta en el correo
 * @param centro nombre del centro desde el que se envia
 * @throws Exception
 */
public void sendByMail(String to, Object attach, String centro) throws Exception {
    logger.debug("          Iniciando la configuracion del mail con sus parametros correspondientes ,"
            + " obtenemos los parametros de environment");

    String dataBase = routingDataSource.dbActual();
    allDataSources.getDatasources();

    Datasources dat = null;
    for (Datasources datas : allDataSources.getDatasources()) {
        if (datas.getNombreDatasource().equals(dataBase)) {
            dat = datas;
            break;
        }
    }
    if (StringUtils.isBlank(StringUtils.trim(dat.getHost()))) {
        throw new Exception(
                "El host es [" + StringUtils.trim(dat.getHost()) + "] , error de host desconocido o erroneo");
    }
    logger.debug("          El host es [" + StringUtils.trim(dat.getHost()) + "]");

    if (StringUtils.isBlank(StringUtils.trim(dat.getUsernameEmail()))) {
        throw new Exception("El usuario es [" + StringUtils.trim(dat.getUsernameEmail())
                + "], error de login en el correo , usuario desconocido o erroneo");
    }
    logger.debug("          El usuario es [" + StringUtils.trim(dat.getUsernameEmail()) + "]");

    if (StringUtils.isBlank(StringUtils.trim(dat.getPasswordEmail()))) {
        throw new Exception("La contrasea es [" + StringUtils.trim(dat.getPasswordEmail())
                + "], error de login en el correo , contrasea desconocida o erronea");
    }
    logger.debug("          La contrasea es [" + StringUtils.trim(dat.getPasswordEmail()) + "]");

    if (StringUtils.isBlank(to)) {
        throw new Exception("El destinatario es [" + to + "], no se especificaron destinatarios.");
    }
    logger.debug("          El destinatario es [" + to + "]");

    /*if (dat.getPort()== null) {
    throw new Exception("El puerto es [" + StringUtils.trim(environment.getProperty("mail.port")) + "], el puerto del servidor de correo falla");
    }*/
    logger.debug("          El puerto es [" + dat.getPort() + "]");

    /*if (StringUtils.isBlank(StringUtils.trim(environment.getProperty("mail.TLS")))) {
    throw new Exception("El TLS es [" + StringUtils.trim(environment.getProperty("mail.TLS")) + "]");
    }*/
    logger.debug("          El TLS es [" + dat.getTLS() + "]");

    System.setProperty("mail.imap.auth.plain.disable", "true");

    MultiPartEmail email = new MultiPartEmail();
    email.setHostName(StringUtils.trim(dat.getHost()));
    email.setAuthenticator(new DefaultAuthenticator(StringUtils.trim(dat.getUsernameEmail()),
            StringUtils.trim(dat.getPasswordEmail())));
    email.setFrom(StringUtils.trim(StringUtils.trim(dat.getUsernameEmail())), centro);
    email.setDebug(true);
    email.setSmtpPort(dat.getPort());
    email.setStartTLSEnabled(dat.getTLS());
    email.setSSLOnConnect(dat.getSSL());
    DataSource source = null;
    if (attach != null) {
        logger.debug("          Adjuntando pdf");
        source = new ByteArrayDataSource((InputStream) attach, "application/pdf");
        email.attach(source, "Pedido de centro " + centro + ".pdf", "Pedido de centro " + centro);
    }
    email.setSubject("Pedido de centro [" + centro + "]");
    logger.debug("          Realizando envio");
    email.addTo(to);
    email.send();

    try {
        if (!StringUtils.isBlank(StringUtils.trim(dat.getMailCC()))) {
            logger.debug("          Enviando a CC: " + dat.getMailCC());
            MultiPartEmail emailCC = new MultiPartEmail();
            emailCC.setHostName(StringUtils.trim(dat.getHost()));
            emailCC.setAuthenticator(new DefaultAuthenticator(StringUtils.trim(dat.getUsernameEmail()),
                    StringUtils.trim(dat.getPasswordEmail())));
            emailCC.setFrom(StringUtils.trim(StringUtils.trim(dat.getUsernameEmail())), centro);
            emailCC.setDebug(true);
            emailCC.setSmtpPort(dat.getPort());
            emailCC.setStartTLSEnabled(dat.getTLS());
            emailCC.setSSLOnConnect(dat.getSSL());
            if (attach != null) {
                logger.debug("          Adjuntando pdf a copia");
                emailCC.attach(source, "Pedido de centro " + centro + ".pdf", "Pedido de centro " + centro);
            }
            emailCC.setSubject("Pedido de centro " + centro);
            emailCC.addCc(StringUtils.split(StringUtils.trim(dat.getMailCC()), ","));
            emailCC.send();
        }
    } catch (Exception e) {
        logger.warn("          Se han producido errores al enviar los CC: " + e.toString());
    }
    logger.debug("     Finalizando envio email");

}

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

public void enviarMail() throws EmailException, SQLException, IOException {
    StringBuilder sb = new StringBuilder();
    MultiPartEmail email = new HtmlEmail();
    try {//  w  w  w.  j  av  a2  s . com
        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:org.agnitas.util.AgnUtils.java

/**
 * Sends the attachment of an email.//  w w w.ja  v  a2 s . co  m
 */
public static boolean sendEmailAttachment(String from, String to_adrList, String cc_adrList, String subject,
        String txt, byte[] att_data, String att_name, String att_type) {
    boolean result = true;

    try {
        // Create the email message
        MultiPartEmail email = new MultiPartEmail();
        email.setCharset("UTF-8");
        email.setHostName(getSmtpMailRelayHostname());
        email.setFrom(from);
        email.setSubject(subject);
        email.setMsg(txt);

        // bounces and reply forwarded to assistance@agnitas.de
        email.addReplyTo("assistance@agnitas.de");
        email.setBounceAddress("assistance@agnitas.de");

        // Set to-recipient email addresses
        InternetAddress[] toAddresses = getEmailAddressesFromList(to_adrList);
        if (toAddresses != null && toAddresses.length > 0) {
            for (InternetAddress singleAdr : toAddresses) {
                email.addTo(singleAdr.getAddress());
            }
        }

        // Set cc-recipient email addresses
        InternetAddress[] ccAddresses = getEmailAddressesFromList(cc_adrList);
        if (ccAddresses != null && ccAddresses.length > 0) {
            for (InternetAddress singleAdr : ccAddresses) {
                email.addCc(singleAdr.getAddress());
            }
        }

        // Create and add the attachment
        ByteArrayDataSource attachment = new ByteArrayDataSource(att_data, att_type);
        email.attach(attachment, att_name, "EMM-Report");

        // send the email
        email.send();
    } catch (Exception e) {
        logger.error("sendEmailAttachment: " + e.getMessage(), e);
        result = false;
    }

    return result;
}

From source file:org.apache.nifi.processors.email.ConsumeEWS.java

public MimeMessage parseMessage(EmailMessage item) throws Exception {
    EmailMessage ewsMessage = item;/*from   w  w  w  . j a  v a2s  . c om*/
    final String bodyText = ewsMessage.getBody().toString();

    MultiPartEmail mm;

    if (ewsMessage.getBody().getBodyType() == BodyType.HTML) {
        mm = new HtmlEmail().setHtmlMsg(bodyText);
    } else {
        mm = new MultiPartEmail();
        mm.setMsg(bodyText);
    }
    mm.setHostName("NiFi-EWS");
    //from
    mm.setFrom(ewsMessage.getFrom().getAddress());
    //to recipients
    ewsMessage.getToRecipients().forEach(x -> {
        try {
            mm.addTo(x.getAddress());
        } catch (EmailException e) {
            throw new ProcessException("Failed to add TO recipient.", e);
        }
    });
    //cc recipients
    ewsMessage.getCcRecipients().forEach(x -> {
        try {
            mm.addCc(x.getAddress());
        } catch (EmailException e) {
            throw new ProcessException("Failed to add CC recipient.", e);
        }
    });
    //subject
    mm.setSubject(ewsMessage.getSubject());
    //sent date
    mm.setSentDate(ewsMessage.getDateTimeSent());
    //add message headers
    ewsMessage.getInternetMessageHeaders().forEach(x -> mm.addHeader(x.getName(), x.getValue()));

    //Any attachments
    if (ewsMessage.getHasAttachments()) {
        ewsMessage.getAttachments().forEach(x -> {
            try {
                FileAttachment file = (FileAttachment) x;
                file.load();

                ByteArrayDataSource bds = new ByteArrayDataSource(file.getContent(), file.getContentType());

                mm.attach(bds, file.getName(), "", EmailAttachment.ATTACHMENT);
            } catch (MessagingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    mm.buildMimeMessage();
    return mm.getMimeMessage();
}