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

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

Introduction

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

Prototype

public Email setSSLOnConnect(final boolean ssl) 

Source Link

Document

Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS).

Usage

From source file:com.github.somi92.seecsk.util.email.EmailSender.java

public static void sendEmail(EmailContainer ec) throws RuntimeException {

    try {/*from w  w  w.  ja v a  2s.c om*/

        String user = Config.vratiInstancu().vratiVrednost(Constants.OrgInfoConfigKeys.ORGANISATION_EMAIL);
        String password = Config.vratiInstancu()
                .vratiVrednost(Constants.OrgInfoConfigKeys.ORGANISATION_EMAIL_PASSWORD);

        EmailAttachment ea = new EmailAttachment();
        ea.setPath(ec.getAttachmentPath());
        ea.setDisposition(EmailAttachment.ATTACHMENT);
        ea.setDescription("Primer ispravno popunjene uplatnice za ?lanarinu");
        ea.setName("uplatnica.pdf");

        MultiPartEmail mpe = new MultiPartEmail();
        mpe.setDebug(true);
        mpe.setAuthenticator(new DefaultAuthenticator(user, password));
        mpe.setHostName(
                Config.vratiInstancu().vratiVrednost(Constants.EmailServerConfigKeys.EMAIL_SERVER_HOST));
        mpe.setSSLOnConnect(true);
        mpe.setStartTLSEnabled(true);
        mpe.setSslSmtpPort(
                Config.vratiInstancu().vratiVrednost(Constants.EmailServerConfigKeys.EMAIL_SERVER_PORT));
        mpe.setSubject(ec.getSubject());
        mpe.setFrom(ec.getFromEmail(),
                Config.vratiInstancu().vratiVrednost(Constants.OrgInfoConfigKeys.ORGANISATION_NAME));
        mpe.setMsg(ec.getMessage());

        mpe.addTo(ec.getToEmail());
        mpe.attach(ea);

        mpe.send();

    } catch (EmailException ex) {
        ex.printStackTrace();
        throw new RuntimeException("Sistem nije uspeo da poalje email. Pokuajte ponovo.");
    }
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailSephoraPassedJava(String from, String grupSephora, String subject, String filename)
        throws FileNotFoundException, IOException {

    try {//from  w w w.j  a v  a 2s .co m

        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath(filename);
        attachment.setDisposition(EmailAttachment.ATTACHMENT);

        attachment.setDescription("rezultat TC-uri");
        attachment.setName("rezultat TC-uri");

        MultiPartEmail email = new MultiPartEmail();

        email.setHostName("smtp.gmail.com");
        email.setSmtpPort(465);

        email.setAuthenticator(new DefaultAuthenticator("anda.cristea@contentspeed.ro", "testtest"));
        email.setSSLOnConnect(true);

        email.addTo(grupSephora);

        //email.addBcc(grupSephora);
        email.setFrom(from, "Teste Automate");
        email.setSubject(subject);
        email.setMsg(subject);

        // add the attachment
        //email.attach(attachment);
        StringWriter writer = new StringWriter();
        IOUtils.copy(new FileInputStream(new File(filename)), writer);

        email.setContent(writer.toString(), "text/html");
        email.attach(attachment);

        email.send();
        writer.close();
    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        ex.printStackTrace();

    }

}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmail(String from, String to1, String to2, String subject, String filename)
        throws FileNotFoundException, IOException {

    try {/*from   w ww. j a v  a 2  s.  c om*/

        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath(filename);
        attachment.setDisposition(EmailAttachment.ATTACHMENT);

        attachment.setDescription("rezultat TC-uri");
        attachment.setName("rezultat TC-uri");

        MultiPartEmail email = new MultiPartEmail();

        email.setHostName("smtp.gmail.com");
        email.setSmtpPort(465);
        //email.setAuthenticator(new DefaultAuthenticator("test@contentspeed.ro", "andaanda"));
        email.setAuthenticator(new DefaultAuthenticator("anda.cristea@contentspeed.ro", "anda.cristea"));
        email.setSSLOnConnect(true);

        email.addBcc(to1);
        email.addBcc(to2);
        email.setFrom(from, "Teste Automate");
        email.setSubject(subject);
        email.setMsg(subject);

        // add the attachment
        //email.attach(attachment);
        StringWriter writer = new StringWriter();
        IOUtils.copy(new FileInputStream(new File(filename)), writer);

        email.setContent(writer.toString(), "text/html");
        email.attach(attachment);

        // send the email
        email.send();
        writer.close();
    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        System.out.println(ex.getMessage());

    }

}

From source file:ec.edu.espe.distribuidas.web.ReportFacturaBean.java

public void testMultiPartEmail() throws UnsupportedEncodingException, EmailException, MalformedURLException {

    EmailAttachment att2 = new EmailAttachment();
    att2.setPath(/*w  w  w .j  av a  2  s . c om*/
            "C:\\Users\\Andres Vr\\Documents\\Git\\ProyectoMaldito7.0\\ProyectMaltido2\\ProyectoMaldito2\\ProyectoMaldito2-web\\src\\main\\webapp\\pdf\\factura.pdf");
    att2.setDisposition(EmailAttachment.ATTACHMENT);
    att2.setDescription("Envio Factura Mantenimiento SpotLinght&Wires");

    MultiPartEmail email = new MultiPartEmail();
    email.setHostName("smtp.gmail.com");
    email.setSmtpPort(587);
    email.setSSLOnConnect(true);
    email.setAuthentication("spotwires@gmail.com", "084383260a");

    email.addTo("avrz237@gmail.com");
    email.setFrom("spotwires@gmail.com");
    email.setSubject("Factura");
    email.setMsg("Adjunto Factura");

    email.attach(att2);

    email.send();
    //            SimpleEmail mail = new SimpleEmail();
    // 
    //        //Configuracion necesaria para GMAIL
    //        mail.setHostName("smtp.gmail.com");
    //        mail.setTLS(true);
    //        mail.setSmtpPort(587);
    //        mail.setSSL(true);
    //        //En esta seccion colocar cuenta de usuario de Gmail y contrasea
    //        mail.setAuthentication("spotwires@gmail.com", "084383260a");
    // 
    //        //Cuenta de Email Destino
    //        mail.addTo("avrz237@gmail.com");
    //        //Cuenta de Email Origen, la misma con la que nos autenticamos
    //        mail.setFrom("spotwires@gmail.com");
    //        //Titulo del Email
    //        mail.setSubject("Email enviado usando Apache Commons Email");
    //        //Contenido del Email
    //        mail.setMsg("Mail enviado usando una cuenta de correo de GMAIL");
    //        mail.send();
}

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

@Ignore
@Test// w w  w. j a  v a2s.c o m
public void send() {
    try {
        MultiPartEmail email = new MultiPartEmail();
        email.setHostName(SMTP);
        email.setAuthenticator(new DefaultAuthenticator(USUARIO, PASSWORD));
        email.setDebug(true);
        email.setSmtpPort(PUERTO);
        email.setStartTLSEnabled(true);

        email.setSSLOnConnect(true);

        email.setFrom(FROM, FROM);
        email.addTo(TO, TO);
        email.setSubject("Correo de Prueba");
        email.attach(new File("/home/jcgonzalez/TMP/a.hl7"));

        email.send();
    } catch (Exception e) {
        logger.error(e.toString());
    }
}

From source file:info.toegepaste.controller.PdfController.java

public void CreatePdf(long studentId) {
    //Fonts/*from w w w.j a v a  2 s. c  o m*/
    Font header = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD);
    Font normal = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL);

    //Declaration
    Student student = new Student();
    List<Course> courses;
    List<Exam> exams = null;
    Score score;
    int totaal = 0; //totaal van een vak berekenen
    int maxScore = 0; //max soore van een test
    int aantalVakken = 0; //aantal vakken waaraan student heeft deelgenomen
    int klasgemiddelde = 0; //hulpvariabele om klasgemiddelde op te vragen
    Double totaalGemiddelde = 0.0; //eindpercentage
    Double vermenigvuldigfactor = 0.0; //om score op 20 weer te geven
    ArrayList<Integer> gemiddeldes = new ArrayList<Integer>(); //gemiddeldes per vak
    ArrayList<Integer> gemiddeldesKlas = new ArrayList<Integer>(); //gemiddelde klas per vak

    PdfPCell cell;

    //Document
    Document document = new Document();

    //student opvullen
    student = pdfService.getStudent(studentId);

    //Tempfix
    //student.getClassgroup();

    //cursussen opvullen
    courses = courseService.getWithClassgroup(student.getClassgroup());

    for (int i = 0; i < courses.size(); i++) {
        //testen opvullen
        exams = pdfService.getExamsByCourse(courses.get(i));
        for (int j = 0; j < exams.size(); j++) {
            score = pdfService.getScoreByExamAndStudent(exams.get(j), student);
            //nagaan of de student heeft deelgenomen aan de test
            if (score != null) {
                // score op 20 weergeven
                vermenigvuldigfactor = 20 / (double) exams.get(j).getTotal();
                totaal += (int) (score.getScore() * vermenigvuldigfactor);
            }
            //klasgemiddelde voor een vak
            klasgemiddelde = pdfService.getAverageScoreByExam(exams.get(j));
            gemiddeldesKlas.add(klasgemiddelde);
        }
        if (exams.size() > 0) {
            gemiddeldes.add(totaal / exams.size());
            totaalGemiddelde += totaal / exams.size();
            aantalVakken++;
        }
        totaal = 0;
        exams.clear();
    }

    totaalGemiddelde = totaalGemiddelde / aantalVakken * 5;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        PdfWriter.getInstance(document, outputStream);

        document.open();
        //header
        document.add(new Paragraph("Studenten Rapport", header));
        document.add(new Paragraph("Student:" + student.getFirstname() + " " + student.getLastname(), normal));
        document.add(new Paragraph("Klas:" + student.getClassgroup(), normal));
        document.add(new Paragraph("Alle scores worden op 20 weergegeven", normal));

        //table
        PdfPTable table = new PdfPTable(3);

        //create tableheaders
        PdfPCell c1 = new PdfPCell(new Phrase("Vak"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("Score"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("Gemiddelde"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
        table.setHeaderRows(1);

        for (int i = 0; i < aantalVakken; i++) {
            cell = new PdfPCell(new Phrase(gemiddeldes.get(i).toString()));
            if (gemiddeldes.get(i) < 10) {
                cell.setBackgroundColor(BaseColor.RED);
            }

            table.addCell(courses.get(i).getName());
            table.addCell(cell);
            table.addCell(gemiddeldesKlas.get(i).toString());
        }

        document.add(table);

        //end
        document.add(new Paragraph("Totaal behaald percentage:" + totaalGemiddelde, normal));
        document.close();

    } catch (DocumentException e) {
        e.printStackTrace();
        //  } catch (FileNotFoundException e) {
        //   e.printStackTrace();
    }
    MultiPartEmail email = new MultiPartEmail();
    email.setHostName("smtp.googlemail.com");
    email.setSmtpPort(587);
    email.setSSLOnConnect(true);
    email.setAuthenticator(new DefaultAuthenticator("bitmescoretracker@gmail.com", "bitmeScore"));
    try {

        email.addTo(student.getEmail());
        email.setFrom("bitmescoretracker@gmail.com");
        email.setSubject("Requested scores , scoretracker");
        email.setMsg("Here are the scores you requested!");

        //  EmailAttachment attachment = new EmailAttachment();
        //attachment.setDescription("PDF met uw punten");
        // attachment.setName(student.getFirstname() + " " + student.getLastname() + " scores");
        byte[] bytes = outputStream.toByteArray();

        DataSource source = new javax.mail.util.ByteArrayDataSource(bytes, "application/pdf");
        System.out.println("Stuff");

        /* try{
         source = outputStream.write(bytes);
         }catch(IOException e){
             e.printStackTrace();
         }*/
        email.attach(source, student.getFirstname() + " " + student.getLastname() + " scores", "stuff");

        email.send();
    } catch (EmailException ex) {
        ex.printStackTrace();
    }

}

From source file:com.jk.mail.MailInfo.java

/**
 * Fill email.//ww  w  .j a  v  a  2s. co m
 *
 * @param email
 *            the email
 * @throws EmailException
 *             the email exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public void fillEmail(final MultiPartEmail email) throws EmailException, IOException {
    email.setHostName(getHost());
    email.setSmtpPort(getSmtpPort());

    email.addTo(getTo());
    email.setFrom(getFrom());
    email.setSubject(getSubject());
    email.setMsg(getMsg());
    email.setSSLOnConnect(isSecured());
    if (isRequiresAuthentication()) {
        email.setAuthentication(getUsername(), getPassword());
    }
    for (int i = 0; i < this.attachements.size(); i++) {
        final Attachment attachment = this.attachements.get(i);
        final ByteArrayDataSource ds = new ByteArrayDataSource(attachment.getData(), attachment.getMimeType());
        email.attach(ds, attachment.getName(), attachment.getDescription());
    }
}

From source file:eu.ggnet.dwoss.mandator.api.value.Mandator.java

/**
 * Prepares a eMail to be send direct over the mandator smtp configuration.
 * The email is missing: to, subject, message and optional attachments.
 *
 * @return the email// www.  j  a  v  a2 s  .  com
 * @throws EmailException if something is wrong in the subsystem.
 */
public MultiPartEmail prepareDirectMail() throws EmailException {
    MultiPartEmail email = new MultiPartEmail();
    email.setHostName(smtpConfiguration.getHostname());
    email.addBcc(company.getEmail());
    email.setFrom(company.getEmail(), company.getEmailName());
    email.setAuthentication(smtpConfiguration.getSmtpAuthenticationUser(),
            smtpConfiguration.getSmtpAuthenticationPass());
    email.setStartTLSEnabled(false);
    email.setSSLCheckServerIdentity(false);
    email.setSSLOnConnect(false);
    email.setCharset(smtpConfiguration.getCharset());
    return email;
}

From source file:com.commander4j.email.JeMail.java

public void postMail(String recipientsTO[], String subject, String message, String attachmentFilename,
        String attachmentLongFilename) throws MessagingException {

    logger.debug("SMTP_AUTH_REQD=" + SMTP_AUTH_REQD);
    logger.debug("MAIL_SMTP_HOST_NAME=" + SMTP_HOST_NAME);
    logger.debug("MAIL_SMTP_AUTH_USER=" + SMTP_AUTH_USER);
    logger.debug("MAIL_SMTP_AUTH_PWD=********");
    logger.debug("MAIL_SMTP_PORT=" + MAIL_SMTP_PORT);
    logger.debug("MAIL_SMTP_SSL_PORT=" + MAIL_SMTP_SSL_PORT);
    logger.debug("MAIL_SMTP_FROM_ADRESS=" + SMTP_FROM_ADRESS);
    logger.debug("MAIL_SMTP_USE_SSL=" + SMTP_USE_SSL);

    //Email email = new SimpleEmail();
    logger.debug("Creating MultiPart Email");
    MultiPartEmail email = new MultiPartEmail();

    logger.debug("Setting Host Name to " + SMTP_HOST_NAME);
    email.setHostName(SMTP_HOST_NAME);/* w  w  w  .j av a2  s .co m*/
    logger.debug("Setting SMTP Port to " + MAIL_SMTP_PORT);
    email.setSmtpPort(Integer.valueOf(MAIL_SMTP_PORT));

    logger.debug("Setting SMTP SSL Port to " + MAIL_SMTP_SSL_PORT);
    email.setSslSmtpPort(MAIL_SMTP_SSL_PORT);

    logger.debug("Setting Use SSL on Connect to  " + SMTP_USE_SSL);
    email.setSSLOnConnect(Boolean.valueOf(SMTP_USE_SSL));

    logger.debug("Authentication Required =  " + SMTP_AUTH_REQD);

    if (SMTP_AUTH_REQD.toUpperCase().equals("TRUE")) {
        email.setAuthenticator(new DefaultAuthenticator(SMTP_AUTH_USER, SMTP_AUTH_PWD));

    }

    logger.debug("Setting SMTP USE SSL =  " + SMTP_USE_SSL);
    email.setSSLOnConnect(Boolean.valueOf(SMTP_USE_SSL));

    logger.debug("Setting SMTP USE TLS =  " + SMTP_USE_TLS);
    email.setStartTLSEnabled(Boolean.valueOf(SMTP_USE_TLS));
    email.setStartTLSRequired(Boolean.valueOf(SMTP_USE_TLS));

    try {
        logger.debug("From Address =  " + SMTP_FROM_ADRESS);
        email.setFrom(SMTP_FROM_ADRESS);
        email.setSubject(subject);
        email.setMsg(message + "\n\n");
        for (int x = 1; x <= recipientsTO.length; x++) {
            logger.debug("Add To Address =  " + recipientsTO[x - 1]);
            email.addTo(recipientsTO[x - 1]);
        }

        if (JUtility.replaceNullStringwithBlank(attachmentFilename).equals("") == false) {
            // Create the attachment
            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath(attachmentLongFilename);
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription(attachmentFilename);
            attachment.setName(attachmentFilename);

            // add the attachment
            logger.debug("Add Attachment");
            email.attach(attachment);
        }

        logger.debug("Sending");
        email.send();
        logger.debug("Sent successfully");
    } catch (EmailException e) {
        logger.error("Unable to send email : " + e.getCause().getMessage());
    }

}

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// w w w  .j  a  v a2s .c om
 * @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");

}