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

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

Introduction

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

Prototype

@Deprecated
public void setSSL(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:emailworkshop.EmailWorkshop.java

public static void enviaEmailComAnexo(String mailFrom, String senhaFrom, String emailTo, String nomeTo)
        throws EmailException {
    // cria o anexo 1.
    EmailAttachment anexo1 = new EmailAttachment();
    anexo1.setPath("Certificado.pdf"); //caminho do arquivo (RAIZ_PROJETO/teste/teste.txt)
    anexo1.setDisposition(EmailAttachment.ATTACHMENT);
    anexo1.setDescription("anexo");
    anexo1.setName("Certificado.pdf");

    // configura o email
    MultiPartEmail email = new MultiPartEmail();
    email.setHostName("smtp.gmail.com"); // o servidor SMTP para envio do e-mail
    email.addTo(emailTo, nomeTo); //destinatrio
    email.setFrom(mailFrom, "UFPR"); // remetente
    email.setSubject("Certificado II Workshop de Inovao"); // assunto do e-mail
    email.setMsg("Segue anexo o Certificado de participaao no II Workshop, Obrigado pela presena! \n "
            + emailTo); //conteudo do e-mail
    email.setAuthentication(mailFrom, senhaFrom);
    email.setSmtpPort(465);/*from  w w w . j a  v a2 s . com*/
    email.setSSL(true);
    email.setTLS(true);
    // adiciona arquivo(s) anexo(s)
    email.attach(anexo1);
    // envia o email
    email.send();
}

From source file:net.big_oh.postoffice.PostOfficeService.java

public void sendMail(Set<String> toRecipients, String subject, String messageText, Set<File> attachments)
        throws EmailException {

    Duration dur = new Duration(this.getClass());
    logger.info("Begin send email to " + toRecipients.size() + " recipient(s) with " + attachments.size()
            + " attachment(s).");

    // validate the method parameters
    if (toRecipients.isEmpty()) {
        throw new IllegalArgumentException("Cowardly refusing to send an email message with no recipients.");
    }/*from  w  w w . j av  a 2s.c o  m*/

    // instantiate an email object
    MultiPartEmail email = new MultiPartEmail();

    // establish SMTP end-point details
    email.setHostName(smtpServerHost);
    email.setSSL(transportWithSsl);
    if (transportWithSsl) {
        email.setSslSmtpPort(Integer.toString(smtpServerPort));
    } else {
        email.setSmtpPort(smtpServerPort);
    }

    // establish SMTP authentication details
    if (!StringUtils.isBlank(smtpUserName) && !StringUtils.isBlank(smtpPassword)) {
        email.setAuthentication(smtpUserName, smtpPassword);
    }
    email.setTLS(authenticateWithTls);

    // establish basic email delivery details
    email.setDebug(debug);
    email.setFrom(sendersFromAddress);
    for (String toRecipient : toRecipients) {
        email.addTo(toRecipient);
    }

    // set email content
    email.setSubject(subject);
    email.setMsg(messageText);

    // create attachments to the email
    for (File file : attachments) {

        if (!file.exists()) {
            logger.error("Skipping attachment file that does not exist: " + file.toString());
            continue;
        }

        if (!file.isFile()) {
            logger.error("Skipping attachment file that is not a normal file: " + file.toString());
            continue;
        }

        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath(file.getPath());
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setName(file.getName());

        email.attach(attachment);

    }

    // Send message
    email.send();

    dur.stop("Finished sending email to " + toRecipients.size() + " recipient(s)");

}

From source file:com.cs.sis.controller.EmailController.java

private MultiPartEmail criarEmail(String destinatario, String assunto, String msg) throws EmailException {
    MultiPartEmail email = new MultiPartEmail();
    email.setHostName(HOST_NAME); // o servidor SMTP para envio do e-mail
    email.addTo(destinatario); //destinatrio
    email.setFrom(EMAIL_REMETENTE); // remetente
    email.setSubject(assunto); // assunto do e-mail
    email.setMsg(msg); //conteudo do e-mail
    email.setAuthentication(EMAIL_REMETENTE, new StringBuffer(EMAIL_SENHA).reverse().toString());
    email.setSmtpPort(465);/*from   ww w. j  a va2  s  . co m*/
    email.setSSL(true);
    email.setTLS(true);
    return email;
}

From source file:com.googlecode.fascinator.portal.process.EmailNotifier.java

public boolean emailAttachment(String from, String recipient, String subject, String body, byte[] attachData,
        String attachDataType, String attachFileName, String attachDesc) throws Exception {
    MultiPartEmail email = new MultiPartEmail();
    email.attach(new ByteArrayDataSource(attachData, attachDataType), attachFileName, attachDesc,
            EmailAttachment.ATTACHMENT);
    log.debug("Email host: " + host);
    log.debug("Email port: " + port);
    log.debug("Email username: " + username);
    log.debug("Email from: " + from);
    log.debug("Email to: " + recipient);
    log.debug("Email Subject is: " + subject);
    log.debug("Email Body is: " + body);
    email.setHostName(host);//from w w  w . ja  v a2s .c  o m
    email.setSmtpPort(Integer.parseInt(port));
    email.setAuthenticator(new DefaultAuthenticator(username, password));
    // the method setSSL is deprecated on the newer versions of commons
    // email...
    email.setSSL("true".equalsIgnoreCase(ssl));
    email.setTLS("true".equalsIgnoreCase(tls));
    email.setFrom(from);
    email.setSubject(subject);
    email.setMsg(body);
    if (recipient.indexOf(",") >= 0) {
        String[] recs = recipient.split(",");
        for (String rec : recs) {
            email.addTo(rec);
        }
    } else {
        email.addTo(recipient);
    }
    email.send();
    return true;
}

From source file:au.edu.ausstage.utils.EmailManager.java

/**
 * A method for sending a simple email message
 *
 * @param subject the subject of the message
 * @param message the text of the message
 * @param attachmentPath the path to the attachment
 *
 * @return true, if and only if, the email is successfully sent
 *//*from  ww  w .  j a  v a2  s.  c  om*/
public boolean sendMessageWithAttachment(String subject, String message, String attachmentPath) {

    // check the input parameters
    if (InputUtils.isValid(subject) == false || InputUtils.isValid(message) == false
            || InputUtils.isValid(attachmentPath) == false) {
        throw new IllegalArgumentException("All parameters are required");
    }

    try {
        // define helper variables
        MultiPartEmail email = new MultiPartEmail();

        // configure the instance of the email class
        email.setSmtpPort(options.getPortAsInt());

        // define authentication if required
        if (InputUtils.isValid(options.getUser()) == true) {
            email.setAuthenticator(new DefaultAuthenticator(options.getUser(), options.getPassword()));
        }

        // turn on / off debugging
        email.setDebug(DEBUG);

        // set the host name
        email.setHostName(options.getHost());

        // set the from email address
        email.setFrom(options.getFromAddress());

        // set the subject
        email.setSubject(subject);

        // set the message
        email.setMsg(message);

        // set the to address
        String[] addresses = options.getToAddress().split(":");

        for (int i = 0; i < addresses.length; i++) {
            email.addTo(addresses[i]);
        }

        // set the security options
        if (options.getTLS() == true) {
            email.setTLS(true);
        }

        if (options.getSSL() == true) {
            email.setSSL(true);
        }

        // build the attachment
        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath(attachmentPath);
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription("Sanitised Twitter Message");
        attachment.setName("twitter-message.txt");

        // add the attachment
        email.attach(attachment);

        // send the email
        email.send();

    } catch (EmailException ex) {
        if (DEBUG) {
            System.err.println("ERROR: Sending of email failed.\n" + ex.toString());
        }

        return false;
    }
    return true;
}

From source file:dk.cubing.liveresults.action.admin.ScoresheetAction.java

/**
 * @return//from w  ww.java  2  s  .  co m
 */
public String exportResults() {
    if (competitionId != null) {
        Competition competitionTemplate = getCompetitionService().find(competitionId);
        if (competitionTemplate == null) {
            log.error("Could not load competition: {}", competitionId);
            return Action.ERROR;
        }
        setCompetition(competitionTemplate);

        try {
            // load WCA template from file
            InputStream is = ServletActionContext.getServletContext()
                    .getResourceAsStream(getSpreadSheetFilename());
            Workbook workBook;
            workBook = WorkbookFactory.create(is);
            is.close();

            // build special registration sheet
            generateRegistrationSheet(workBook, getCompetition());

            // build result sheets
            generateResultSheets(workBook, getCompetition());

            // set default selected sheet
            workBook.setActiveSheet(workBook.getSheetIndex(SHEET_TYPE_REGISTRATION));

            // email or just output to pdf?
            if (isSubmitResultsToWCA()) {
                // write workbook to temp file
                File temp = File.createTempFile(getCompetitionId(), ".xls");
                temp.deleteOnExit();
                OutputStream os = new FileOutputStream(temp);
                workBook.write(os);
                os.close();

                // Create the attachment
                EmailAttachment attachment = new EmailAttachment();
                attachment.setPath(temp.getPath());
                attachment.setDisposition(EmailAttachment.ATTACHMENT);
                attachment.setName(getCompetitionId() + ".xls");

                // send email
                MultiPartEmail email = new MultiPartEmail();
                email.setCharset(Email.ISO_8859_1);
                email.setHostName(getText("email.smtp.server"));
                if (!getText("email.username").isEmpty() && !getText("email.password").isEmpty()) {
                    email.setAuthentication(getText("email.username"), getText("email.password"));
                }
                email.setSSL("true".equals(getText("email.ssl")));
                email.setSubject("Results from " + getCompetition().getName());
                email.setMsg(getText("admin.export.message",
                        new String[] { getCompetition().getName(), getCompetition().getOrganiser() }));
                email.setFrom(getCompetition().getOrganiserEmail(), getCompetition().getOrganiser());
                email.addTo(getText("admin.export.resultsteamEmail"), getText("admin.export.resultsteam"));
                email.addCc(getCompetition().getOrganiserEmail(), getCompetition().getOrganiser());
                email.addCc(getCompetition().getWcaDelegateEmail(), getCompetition().getWcaDelegate());
                email.attach(attachment);
                email.send();

                return Action.SUCCESS;
            } else {
                // output generated spreadsheet
                log.debug("Ouputting generated workbook");
                out = new ByteArrayOutputStream();
                workBook.write(out);
                out.close();

                return "spreadsheet";
            }
        } catch (InvalidFormatException e) {
            log.error("Spreadsheet template are using an unsupported format.", e);
        } catch (IOException e) {
            log.error("Error reading spreadsheet template.", e);
        } catch (EmailException e) {
            log.error(e.getMessage(), e);
        }
        return Action.ERROR;
    } else {
        return Action.INPUT;
    }
}

From source file:org.igov.io.mail.Mail.java

public void sendOld() throws EmailException {
    LOG.info("init");
    try {/*from   w ww .j  a  v a2  s . co  m*/
        MultiPartEmail oMultiPartEmail = new MultiPartEmail();
        LOG.info("(getHost()={})", getHost());
        oMultiPartEmail.setHostName(getHost());

        String[] asTo = { sMailOnly(getTo()) };
        if (getTo().contains("\\,")) {
            asTo = getTo().split("\\,");//sTo
            for (String s : asTo) {
                LOG.info("oMultiPartEmail.addTo (s={})", s);
                oMultiPartEmail.addTo(s, "receiver");
            }
        }

        LOG.info("(getFrom()={})", getFrom());
        LOG_BIG.debug("(getFrom()={})", getFrom());
        oMultiPartEmail.setFrom(getFrom(), getFrom());//"iGov"
        oMultiPartEmail.setSubject(getHead());
        LOG.info("getHead()={}", getHead());
        String sLogin = getAuthUser();
        if (sLogin != null && !"".equals(sLogin.trim())) {
            oMultiPartEmail.setAuthentication(sLogin, getAuthPassword());
            LOG.info("withAuth");
        } else {
            LOG.info("withoutAuth");
        }
        //oMultiPartEmail.setAuthentication(getAuthUser(), getAuthPassword());
        LOG.info("(getAuthUser()={})", getAuthUser());
        //LOG.info("getAuthPassword()=" + getAuthPassword());
        oMultiPartEmail.setSmtpPort(getPort());
        LOG.info("(getPort()={})", getPort());
        oMultiPartEmail.setSSL(isSSL());
        LOG.info("(isSSL()={})", isSSL());
        oMultiPartEmail.setTLS(isTLS());
        LOG.info("(isTLS()={})", isTLS());

        oSession = oMultiPartEmail.getMailSession();
        MimeMessage oMimeMessage = new MimeMessage(oSession);

        //oMimeMessage.setFrom(new InternetAddress(getFrom(), "iGov", DEFAULT_ENCODING));
        oMimeMessage.setFrom(new InternetAddress(getFrom(), getFrom()));
        //oMimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(sTo, sToName, DEFAULT_ENCODING));
        String sReceiverName = "receiver";
        if (asTo.length == 1) {
            sReceiverName = getToName();
        }
        for (String s : asTo) {
            LOG.info("oMimeMessage.addRecipient (s={})", s);
            //oMultiPartEmail.addTo(s, "receiver");
            oMimeMessage.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(s, sReceiverName, DEFAULT_ENCODING));
        }

        //oMimeMessage.addRecipient(Message.RecipientType.TO,
        //        new InternetAddress(sTo, "recipient", DEFAULT_ENCODING));
        //new InternetAddress(getTo(), "recipient", DEFAULT_ENCODING));
        oMimeMessage.setSubject(getHead(), DEFAULT_ENCODING);

        _AttachBody(getBody());
        //LOG.info("(getBody()={})", getBody());
        oMimeMessage.setContent(oMultiparts);

        //            oMimeMessage.getRecipients(Message.RecipientType.CC);
        //methodCallRunner.registrateMethod(Transport.class.getName(), "send", new Object[]{oMimeMessage});
        Transport.send(oMimeMessage);
        LOG.info("Send " + getTo() + "!!!!!!!!!!!!!!!!!!!!!!!!");
    } catch (Exception oException) {
        LOG.error("FAIL: {} (getTo()={})", oException.getMessage(), getTo());
        LOG.trace("FAIL:", oException);
        throw new EmailException("Error happened when sending email (" + getTo() + ")" + "Exception message: "
                + oException.getMessage(), oException);
    }
    LOG.info("SUCCESS: Sent!");
}

From source file:org.sakaiproject.nakamura.email.outgoing.LiteOutgoingEmailMessageListener.java

/**
 * Set transfer options on the email based on configuration of this service.
 *
 * @param email The email where to set options.
 *//*from w ww. j a va2 s.c o m*/
private void setOptions(MultiPartEmail email) {
    email.setHostName(smtpServer);
    email.setTLS(useTls);
    email.setSSL(useSsl);
    if (useSsl) {
        email.setSslSmtpPort(Integer.toString(smtpPort));
    } else {
        email.setSmtpPort(smtpPort);
    }

    if (!StringUtils.isBlank(authUser) && !StringUtils.isBlank(authPass)) {
        email.setAuthentication(authUser, authPass);
    }
}

From source file:org.wf.dp.dniprorada.util.Mail.java

@Override
public void send() throws EmailException {

    try {/*from   w w  w.j ava2  s.  co m*/
        log.info("init");
        MultiPartEmail oMultiPartEmail = new MultiPartEmail();
        oMultiPartEmail.setHostName(getHost());
        log.info("getHost()=" + getHost());
        oMultiPartEmail.addTo(getTo(), "receiver");
        log.info("getTo()=" + getTo());
        oMultiPartEmail.setFrom(getFrom(), getFrom());//"iGov"
        log.info("getFrom()=" + getFrom());
        oMultiPartEmail.setSubject(getHead());
        log.info("getHead()=" + getHead());

        oMultiPartEmail.setAuthentication(getAuthUser(), getAuthPassword());
        log.info("getAuthUser()=" + getAuthUser());
        log.info("getAuthPassword()=" + getAuthPassword());
        oMultiPartEmail.setSmtpPort(getPort());
        log.info("getPort()=" + getPort());
        oMultiPartEmail.setSSL(isSSL());
        log.info("isSSL()=" + isSSL());
        oMultiPartEmail.setTLS(isTLS());
        log.info("isTLS()=" + isTLS());

        oSession = oMultiPartEmail.getMailSession();
        MimeMessage oMimeMessage = new MimeMessage(oSession);

        //oMimeMessage.setFrom(new InternetAddress(getFrom(), "iGov", DEFAULT_ENCODING));
        oMimeMessage.setFrom(new InternetAddress(getFrom(), getFrom()));
        //oMimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(sTo, sToName, DEFAULT_ENCODING));
        oMimeMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(getTo(), "recipient", DEFAULT_ENCODING));

        oMimeMessage.setSubject(getHead(), DEFAULT_ENCODING);

        _Attach(getBody());

        oMimeMessage.setContent(oMultiparts);

        //            oMimeMessage.getRecipients(Message.RecipientType.CC);
        Transport.send(oMimeMessage);
        log.info("[send]:Transport.send!");
    } catch (Exception exc) {
        log.error("[send]", exc);
        throw new EmailException("Error happened when sending email", exc);
    }
}

From source file:projetohorus.EnvioEmail.java

public void EnvioEmail() throws EmailException {
    EmailAttachment anexo1 = new EmailAttachment();
    anexo1.setPath("tesfinal11.pdf"); //caminho do arquivo (RAIZ_PROJETO/teste/teste.txt)
    anexo1.setDisposition(EmailAttachment.ATTACHMENT);
    anexo1.setDescription("PDF");
    anexo1.setName("ProjetoHorus.pdf");

    MultiPartEmail emails = new MultiPartEmail();
    emails.setHostName("smtp.gmail.com"); // o servidor SMTP para envio do e-mail
    emails.addTo("", "Anderson"); //destinatrio
    emails.setFrom("projecthorusifrn@gmail.com", "Projeto");
    emails.setSubject("Teste -> Email com anexo");
    emails.setMsg("conteudo");
    emails.setAuthentication("email", "senha");
    emails.setSmtpPort(465);// w w  w .  ja  va  2s.c  o  m
    emails.setSSL(true);
    emails.setTLS(true);
    emails.attach(anexo1);
    emails.send();

}