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

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

Introduction

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

Prototype

public void setHostName(final String aHostName) 

Source Link

Document

Set the hostname of the outgoing mail server.

Usage

From source file:br.com.hslife.imobiliaria.service.EmailService.java

/**
 * Envia email no formato HTML/*w w w. j a  v  a  2s . c o  m*/
 *
 * @param nomeRemetente
 * @param nomeDestinatario
 * @param emailRemetente
 * @param emailDestinatario
 * @param assunto
 * @param mensagem
 * @param anexo
 *
 * @throws EmailException
 * @throws MalformedURLException
 */
public void enviaEmailFormatoHtml(String nomeRementente, String emailRemetente, String nomeDestinatario,
        String emailDestinatario, String assunto, StringBuilder mensagem, String anexo)
        throws EmailException, MalformedURLException {

    HtmlEmail email = new HtmlEmail();

    // adiciona uma imagem ao corpo da mensagem e retorna seu id
    URL url = new URL(anexo); // URL do arquivo a ser anexado
    String cid = email.embed(url, "Anexos");

    // configura a mensagem para o formato HTML
    email.setHtmlMsg("<html>Anexos</html>");

    // configure uma mensagem alternativa caso o servidor no suporte HTML
    email.setTextMsg("Seu servidor de e-mail no suporta mensagem HTML");

    email.setHostName("smtp.hslife.com.br"); // o servidor SMTP para envio do e-mail
    email.addTo(emailDestinatario, nomeDestinatario); //destinatrio
    email.setFrom(emailRemetente, nomeRementente); // remetente
    email.setSubject(assunto); // assunto do e-mail
    email.setMsg(mensagem.toString()); //conteudo do e-mail
    email.setAuthentication("realimoveis@hslife.com.br", "real123");
    //email.setSmtpPort(465);
    //email.setSSL(true);
    //email.setTLS(true);

    // envia email
    email.send();
}

From source file:br.com.hslife.catu.service.EmailService.java

/**
 * Envia email no formato HTML/*from  www  .ja  va  2  s. c o  m*/
 *
 * @param nomeRemetente
 * @param nomeDestinatario
 * @param emailRemetente
 * @param emailDestinatario
 * @param assunto
 * @param mensagem
 * @param anexo
 *
 * @throws EmailException
 * @throws MalformedURLException
 */
public void enviaEmailFormatoHtml(String nomeRementente, String emailRemetente, String nomeDestinatario,
        String emailDestinatario, String assunto, StringBuilder mensagem, String anexo)
        throws EmailException, MalformedURLException {

    HtmlEmail email = new HtmlEmail();

    // adiciona uma imagem ao corpo da mensagem e retorna seu id
    URL url = new URL(anexo); // URL do arquivo a ser anexado
    String cid = email.embed(url, "Anexos");

    // configura a mensagem para o formato HTML
    email.setHtmlMsg("<html>Anexos</html>");

    // configure uma mensagem alternativa caso o servidor no suporte HTML
    email.setTextMsg("Seu servidor de e-mail no suporta mensagem HTML");

    email.setHostName("smtp.hslife.com.br"); // o servidor SMTP para envio do e-mail
    email.addTo(emailDestinatario, nomeDestinatario); //destinatrio
    email.setFrom(emailRemetente, nomeRementente); // remetente
    email.setSubject(assunto); // assunto do e-mail
    email.setMsg(mensagem.toString()); //conteudo do e-mail
    email.setAuthentication("realimoveis@hslife.com.br", "real123");
    email.setCharset("UTF8");
    //email.setSmtpPort(465);
    //email.setSSL(true);
    //email.setTLS(true);

    // envia email
    email.send();
}

From source file:de.jaide.courier.email.MessageHandlerEMail.java

public void handleMessage(Map<String, Object> parameters) throws CourierException {
    /*// w w w . ja v a 2s .c om
     * Check if the obligatory parameters are there.
     */
    for (String key : obligatoryMappingParameters)
        if (!parameters.containsKey(key))
            throw new CourierException(new MissingParameterException(
                    "The parameter '" + key + "' was expected but couldn't be found."));

    /*
     * Now retrieve the obligatory parameters.
     */
    String configurationName = (String) parameters.get(MAPPING_PARAM_CONFIGURATION_NAME);
    String templatePath = (String) parameters.get(MAPPING_PARAM_TEMPLATE_PATH);
    if ((templatePath != null) && (!templatePath.endsWith("/")))
        templatePath += "/";
    else if (templatePath == null)
        templatePath = "/";

    Class<?> templatePathClass = (Class<?>) parameters.get(MAPPING_PARAM_TEMPLATE_PATH_CLASS);
    File templatePathFile = (File) parameters.get(MAPPING_PARAM_TEMPLATE_PATH_FILE);

    String templateName = (String) parameters.get(MAPPING_PARAM_TEMPLATE_NAME);
    TemplateTypeEnum templateTypeEnum = (TemplateTypeEnum) parameters.get(MAPPING_PARAM_TEMPLATE_TYPE);
    String recipientFirstname = (String) parameters.get(MAPPING_PARAM_RECIPIENT_FIRSTNAME);
    String recipientLastname = (String) parameters.get(MAPPING_PARAM_RECIPIENT_LASTNAME);
    String recipientEMail = (String) parameters.get(MAPPING_PARAM_RECIPIENT_EMAIL);
    String ccRecipientFirstname = (String) parameters.get(MAPPING_PARAM_CC_RECIPIENT_FIRSTNAME);
    String ccRecipientLastname = (String) parameters.get(MAPPING_PARAM_CC_RECIPIENT_LASTNAME);
    String ccRecipientEMail = (String) parameters.get(MAPPING_PARAM_CC_RECIPIENT_EMAIL);

    /*
     * The next three parameters are optional, as they might also be specified in the SMTP configuration file. If they are specified they
     * tell us to overwrite what was specified in the SMTP configuration file and use those values (firstname, lastname, e-mail) for the
     * sender instead.
     */
    String senderFirstname = null;
    if (parameters.containsKey(MAPPING_PARAM_SENDER_FIRSTNAME))
        senderFirstname = (String) parameters.get(MAPPING_PARAM_SENDER_FIRSTNAME);

    String senderLastname = null;
    if (parameters.containsKey(MAPPING_PARAM_SENDER_LASTNAME))
        senderLastname = (String) parameters.get(MAPPING_PARAM_SENDER_LASTNAME);

    String senderEMail = null;
    if (parameters.containsKey(MAPPING_PARAM_SENDER_EMAIL))
        senderEMail = (String) parameters.get(MAPPING_PARAM_SENDER_EMAIL);

    /*
     * Will be used for parsing the templates.
     */
    StringWriter writer = new StringWriter();

    try {
        /*
         * Construct the template that we're about to process. First set the path to load the template(s) from. In case a Directory was given
         * as the base for template loading purposes use that instead.
         */
        if (templatePathFile == null) {
            if (templatePathClass == null)
                templatingConfiguration.setClassForTemplateLoading(getClass(), templatePath);
            else
                templatingConfiguration.setClassForTemplateLoading(templatePathClass, templatePath);
        } else
            templatingConfiguration.setDirectoryForTemplateLoading(templatePathFile);

        /*
         * Get the headers and Freemarker-parse them. If there are no headers then ignore the errors. The file has to be one header per line,
         * header name and value separated by a colon (":").
         */
        Template template;

        Map<String, String> headers = new HashMap<String, String>();
        String headersFilename = retrieveTemplateFilename(templateName,
                MessageHandlerEMail.TEMPLATENAME_SUFFIX_HEADERS, true);
        if (headersFilename != null) {
            try {
                template = loadTemplate(headersFilename);
                template.process(parameters, writer);
                BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
                headers = new HashMap<String, String>();
                String str = "";
                while ((str = reader.readLine()) != null) {
                    String[] split = str.split(":");
                    if (split.length > 1)
                        headers.put(split[0].trim(), split[1].trim());
                }
            } catch (IOException ioe) {
                // The header file is optional, hence we don't care if it couldn't be found
            }
        }

        /*
         * Get the subject line and Freemarker-parse it.
         */
        String subject = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_SUBJECT,
                templateName, false);

        /*
         * Get the body content and Freemarker-parse it.
         */
        String contentText = null;
        String contentHtml = null;

        /*
         * Load all requested versions of the template.
         */
        if (templateTypeEnum == TemplateTypeEnum.TEXT) {
            contentText = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY,
                    templateName, false);
        } else if (templateTypeEnum == TemplateTypeEnum.HTML) {
            contentHtml = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY,
                    templateName, true);
        } else if (templateTypeEnum == TemplateTypeEnum.BOTH) {
            contentText = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY,
                    templateName, false);
            contentHtml = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY,
                    templateName, true);
        } else if (templateTypeEnum == TemplateTypeEnum.ANY) {
            try {
                contentText = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY,
                        templateName, false);
            } catch (IOException ioe) {
            } finally {
                try {
                    contentHtml = loadAndProcessTemplate(parameters,
                            MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY, templateName, true);
                } catch (IOException ioe) {
                    throw new RuntimeException(
                            "Neither the HTML nor the TEXT-only version of the e-mail template '" + templateName
                                    + "' could be found. Are you sure they reside in '" + templatePath
                                    + "' as '" + templateName + "_body.ftl.html' or '" + templateName
                                    + "_body.ftl.txt'?",
                            ioe);
                }
            }
        }

        /*
         * Set the parameters that are identical for that sender, for all recipients.
         * Note: attachments may not be removed once they have been attached, hence the performance-improving caching had to be removed.
         */
        SmtpConfiguration smtpConfiguration = (SmtpConfiguration) smtpConfigurations.get(configurationName);
        HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setCharset("UTF-8");
        htmlEmail.setHostName(smtpConfiguration.getSmtpHostname());
        htmlEmail.setSmtpPort(smtpConfiguration.getSmtpPort());
        if (smtpConfiguration.isTls()) {
            htmlEmail.setAuthenticator(
                    new DefaultAuthenticator(smtpConfiguration.getUsername(), smtpConfiguration.getPassword()));
            htmlEmail.setStartTLSEnabled(smtpConfiguration.isTls());
        }
        htmlEmail.setSSLOnConnect(smtpConfiguration.isSsl());

        /*
         * Changing the sender, to differ from what was specified in the particular SMTP configuration, is optional. As explained above this
         * will only happen if they were specified by the caller.
         */
        if ((senderFirstname != null) || (senderLastname != null) || (senderEMail != null))
            htmlEmail.setFrom(senderEMail, senderFirstname + " " + senderLastname);
        else
            htmlEmail.setFrom(smtpConfiguration.getFromEMail(), smtpConfiguration.getFromSenderName());

        /*
         * Set the parameters that differ for each recipient.
         */
        htmlEmail.addTo(recipientEMail, recipientFirstname + " " + recipientLastname);
        if ((ccRecipientFirstname != null) && (ccRecipientLastname != null) && (ccRecipientEMail != null))
            htmlEmail.addCc(ccRecipientEMail, ccRecipientFirstname + " " + ccRecipientLastname);
        htmlEmail.setHeaders(headers);
        htmlEmail.setSubject(subject);

        /*
         * Set the HTML and Text version of the e-mail body.
         */
        if (contentHtml != null)
            htmlEmail.setHtmlMsg(contentHtml);
        if (contentText != null)
            htmlEmail.setTextMsg(contentText);

        /*
         * Add attachments, if available.
         */
        if (parameters.containsKey(MAPPING_PARAM_ATTACHMENTS)) {
            @SuppressWarnings("unchecked")
            List<EmailAttachment> attachments = (List<EmailAttachment>) parameters
                    .get(MAPPING_PARAM_ATTACHMENTS);
            for (EmailAttachment attachment : attachments) {
                htmlEmail.attach(attachment);
            }
        }

        /*
         * Finished - now send the e-mail.
         */
        htmlEmail.send();
    } catch (IOException ioe) {
        throw new CourierException(ioe);
    } catch (TemplateException te) {
        throw new CourierException(te);
    } catch (EmailException ee) {
        throw new CourierException(ee);
    } finally {
        if (writer != null) {
            writer.flush();

            try {
                writer.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}

From source file:com.smi.travel.util.Mail.java

public String sendmailwithAttchfile(String sendTo, String subject, String content, String attachfile,
        String sendCc) throws EmailException {
    String result = "";
    boolean send = false;
    EmailAttachment attachment = new EmailAttachment();
    HtmlEmail email = new HtmlEmail();
    try {//from   w w w .j av  a2s .c  om
        if ((attachfile != null) && (!attachfile.equalsIgnoreCase(""))) {
            //attachment.setPath("C:\\Users\\Surachai\\Documents\\NetBeansProjects\\SMITravel\\test.txt");
            attachment.setPath(attachfile);
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription("file attachment");
            attachment.setName("text.txt");
            email.attach(attachment);
        }
        send = true;
    } catch (EmailException ex) {
        System.out.println("Email Exception");
        ex.printStackTrace();
        result = "fail";
    }
    if (send) {
        System.out.println(mail.getUsername() + mail.getPassword());
        email.setHostName(mail.getHostname());
        email.setSmtpPort(mail.getPort());
        email.setAuthentication(mail.getUsername(), mail.getPassword());
        email.setSSLOnConnect(true);
        email.setFrom(mail.getUsername());
        email.setSubject(subject);
        email.setHtmlMsg(content);
        String[] toSplit = sendTo.split("\\,");
        for (int i = 0; i < toSplit.length; i++) {
            System.out.println("Print toSplit" + toSplit[i]);
            email.addTo(toSplit[i]);
        }
        if (!sendCc.isEmpty()) {
            String[] ccSplit = sendCc.split("\\,");
            for (int i = 0; i < ccSplit.length; i++) {
                System.out.println("Print ccSplit" + ccSplit[i]);
                email.addCc(ccSplit[i]);
            }
        }
        email.send();

        result = "success";

    }
    return result;
}

From source file:Email.CommonsEmail.java

/**
 * Envia email no formato HTML//from  w w  w. j  a  va2 s. c  o  m
 *
 * @throws EmailException
 * @throws MalformedURLException
 */
private void enviaEmailFormatoHtml() throws EmailException, MalformedURLException, IOException, Exception {

    String para = "alessandropereirarezende@gmail.com;alessandrorezende@msn.com";
    StringTokenizer stPara = new StringTokenizer(para, ";");
    while (stPara.hasMoreTokens()) {

        HtmlEmail email = new HtmlEmail();
        // adiciona uma imagem ao corpo da mensagem e retorna seu id
        URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
        String cid = email.embed(url, "Apache logo");
        System.out.println(cid);

        // configura a mensagem para o formato HTML
        File img = new File(Functions.getCurrentPath() + "web\\resources\\images\\facom.png");
        StringBuilder msg = new StringBuilder();
        msg.append("<html><body>");
        msg.append("<img src=cid:").append(email.embed(img)).append(">");
        msg.append("</body></html>");

        // configure uma mensagem alternativa caso o servidor no suporte HTML
        email.setTextMsg("Seu servidor de e-mail no suporta mensagem HTML");
        // o servidor SMTP para envio do e-mail
        email.setHostName("smtp.gmail.com");
        // remetente
        email.setFrom(emailConfig.getEmail(), emailConfig.getNome());
        email.setAuthentication(emailConfig.getUsuario(), emailConfig.getSenha());
        email.setSmtpPort(emailConfig.getPorta());
        email.setSSLOnConnect(emailConfig.getSsl());

        //destinatrio
        //email.addTo("alessandropereirarezende@gmail.com", "Alessandro");
        email.addTo(stPara.nextToken().trim());
        // assunto do e-mail
        email.setSubject("Teste -> Html Email");
        email.setHtmlMsg(msg.toString());
        //conteudo do e-mail
        //email.setMsg("Teste de Email HTML utilizando commons-email");
        // envia email
        email.send();
    }
}

From source file:fr.gouv.culture.thesaurus.util.MailUtil.java

/**
 * /*w ww .  java 2 s  .c o m*/
 * Envoi l'email.
 * 
 * @throws EmailException
 *             Erreur lors de l'envoi de l'email.
 */
public void send() throws EmailException {

    if (hostProperty == null) {
        log.error("Session email non initialise : envoi des emails impossible.");
        return;
    }

    HtmlEmail email = new HtmlEmail();
    email.setHostName(hostProperty);

    // To
    if (to != null) {
        for (String adresse : to) {
            email.addTo(adresse);
        }
    }

    // Cc
    if (cc != null) {
        for (String adresse : cc) {
            email.addCc(adresse);
        }
    }

    // Cci
    if (cci != null) {
        for (String adresse : cci) {
            email.addBcc(adresse);
        }
    }

    // Subject
    email.setSubject(subjectPrefix != null ? subjectPrefix + subject : subject);

    // From
    email.setFrom(StringUtils.isNotEmpty(from) ? from : defaultFrom);

    // Message & Html
    if (message != null) {
        email.setTextMsg(message);
    }
    if (html != null) {
        email.setHtmlMsg(html);
    }

    if (StringUtils.isNotEmpty(this.charset)) {
        email.setCharset(this.charset);
    }

    email.buildMimeMessage();

    // Attachments
    for (AttachmentBean attachement : attachments) {
        email.attach(attachement.getDataSource(), attachement.getName(), attachement.getDescription());
    }

    email.sendMimeMessage();

}

From source file:com.baasbox.service.user.UserService.java

public static void sendResetPwdMail(String appCode, ODocument user) throws Exception {
    final String errorString = "Cannot send mail to reset the password: ";

    //check method input
    if (!user.getSchemaClass().getName().equalsIgnoreCase(UserDao.MODEL_NAME))
        throw new PasswordRecoveryException(errorString + " invalid user object");

    //initialization
    String siteUrl = Application.NETWORK_HTTP_URL.getValueAsString();
    int sitePort = Application.NETWORK_HTTP_PORT.getValueAsInteger();
    if (StringUtils.isEmpty(siteUrl))
        throw new PasswordRecoveryException(errorString + " invalid site url (is empty)");

    String textEmail = PasswordRecovery.EMAIL_TEMPLATE_TEXT.getValueAsString();
    String htmlEmail = PasswordRecovery.EMAIL_TEMPLATE_HTML.getValueAsString();
    if (StringUtils.isEmpty(htmlEmail))
        htmlEmail = textEmail;// w w  w .  j  a  va  2  s  .  c  om
    if (StringUtils.isEmpty(htmlEmail))
        throw new PasswordRecoveryException(errorString + " text to send is not configured");

    boolean useSSL = PasswordRecovery.NETWORK_SMTP_SSL.getValueAsBoolean();
    boolean useTLS = PasswordRecovery.NETWORK_SMTP_TLS.getValueAsBoolean();
    String smtpHost = PasswordRecovery.NETWORK_SMTP_HOST.getValueAsString();
    int smtpPort = PasswordRecovery.NETWORK_SMTP_PORT.getValueAsInteger();
    if (StringUtils.isEmpty(smtpHost))
        throw new PasswordRecoveryException(errorString + " SMTP host is not configured");

    String username_smtp = null;
    String password_smtp = null;
    if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) {
        username_smtp = PasswordRecovery.NETWORK_SMTP_USER.getValueAsString();
        password_smtp = PasswordRecovery.NETWORK_SMTP_PASSWORD.getValueAsString();
        if (StringUtils.isEmpty(username_smtp))
            throw new PasswordRecoveryException(errorString + " SMTP username is not configured");
    }
    String emailFrom = PasswordRecovery.EMAIL_FROM.getValueAsString();
    String emailSubject = PasswordRecovery.EMAIL_SUBJECT.getValueAsString();
    if (StringUtils.isEmpty(emailFrom))
        throw new PasswordRecoveryException(errorString + " sender email is not configured");

    try {
        String userEmail = ((ODocument) user.field(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER)).field("email")
                .toString();

        String username = (String) ((ODocument) user.field("user")).field("name");

        //Random
        String sRandom = appCode + "%%%%" + username + "%%%%" + UUID.randomUUID();
        String sBase64Random = new String(Base64.encodeBase64(sRandom.getBytes()));

        //Save on DB
        ResetPwdDao.getInstance().create(new Date(), sBase64Random, user);

        //Send mail
        HtmlEmail email = null;

        URL resetUrl = new URL(Application.NETWORK_HTTP_SSL.getValueAsBoolean() ? "https" : "http", siteUrl,
                sitePort, "/user/password/reset/" + sBase64Random);

        //HTML Email Text
        ST htmlMailTemplate = new ST(htmlEmail, '$', '$');
        htmlMailTemplate.add("link", resetUrl);
        htmlMailTemplate.add("user_name", username);
        htmlMailTemplate.add("token", sBase64Random);

        //Plain text Email Text
        ST textMailTemplate = new ST(textEmail, '$', '$');
        textMailTemplate.add("link", resetUrl);
        textMailTemplate.add("user_name", username);
        textMailTemplate.add("token", sBase64Random);

        email = new HtmlEmail();

        email.setHtmlMsg(htmlMailTemplate.render());
        email.setTextMsg(textMailTemplate.render());

        //Email Configuration
        email.setSSL(useSSL);
        email.setSSLOnConnect(useSSL);
        email.setTLS(useTLS);
        email.setStartTLSEnabled(useTLS);
        email.setStartTLSRequired(useTLS);
        email.setSSLCheckServerIdentity(false);
        email.setSslSmtpPort(String.valueOf(smtpPort));
        email.setHostName(smtpHost);
        email.setSmtpPort(smtpPort);
        email.setCharset("utf-8");

        if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) {
            email.setAuthenticator(new DefaultAuthenticator(username_smtp, password_smtp));
        }
        email.setFrom(emailFrom);
        email.addTo(userEmail);

        email.setSubject(emailSubject);
        if (BaasBoxLogger.isDebugEnabled()) {
            StringBuilder logEmail = new StringBuilder().append("HostName: ").append(email.getHostName())
                    .append("\n").append("SmtpPort: ").append(email.getSmtpPort()).append("\n")
                    .append("SslSmtpPort: ").append(email.getSslSmtpPort()).append("\n")

                    .append("SSL: ").append(email.isSSL()).append("\n").append("TLS: ").append(email.isTLS())
                    .append("\n").append("SSLCheckServerIdentity: ").append(email.isSSLCheckServerIdentity())
                    .append("\n").append("SSLOnConnect: ").append(email.isSSLOnConnect()).append("\n")
                    .append("StartTLSEnabled: ").append(email.isStartTLSEnabled()).append("\n")
                    .append("StartTLSRequired: ").append(email.isStartTLSRequired()).append("\n")

                    .append("SubType: ").append(email.getSubType()).append("\n")
                    .append("SocketConnectionTimeout: ").append(email.getSocketConnectionTimeout()).append("\n")
                    .append("SocketTimeout: ").append(email.getSocketTimeout()).append("\n")

                    .append("FromAddress: ").append(email.getFromAddress()).append("\n").append("ReplyTo: ")
                    .append(email.getReplyToAddresses()).append("\n").append("BCC: ")
                    .append(email.getBccAddresses()).append("\n").append("CC: ").append(email.getCcAddresses())
                    .append("\n")

                    .append("Subject: ").append(email.getSubject()).append("\n")

                    //the following line throws a NPE in debug mode
                    //.append("Message: ").append(email.getMimeMessage().getContent()).append("\n")

                    .append("SentDate: ").append(email.getSentDate()).append("\n");
            BaasBoxLogger.debug("Password Recovery is ready to send: \n" + logEmail.toString());
        }
        email.send();

    } catch (EmailException authEx) {
        BaasBoxLogger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(authEx));
        throw new PasswordRecoveryException(
                errorString + " Could not reach the mail server. Please contact the server administrator");
    } catch (Exception e) {
        BaasBoxLogger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(e));
        throw new Exception(errorString, e);
    }

}

From source file:bean.OrdemBean.java

private void enviarEmailOrdem(OrdOrdem ordemNova, boolean novaOrdem) {
    try {/*from   ww w .  ja  va  2 s .c om*/
        String emailAutenticacao = "chravent@gmail.com";
        String senhaAutenticacao = "23421Felix";

        //MultiPartEmail email = new MultiPartEmail();
        HtmlEmail emailOrdem = new HtmlEmail();
        //Informaes do Servidor
        emailOrdem.setHostName("smtp.gmail.com");
        emailOrdem.setSmtpPort(587);
        //DADOS DE QUEM ESTA ENVIANDO O E-MAIL
        emailOrdem.setFrom(emailAutenticacao, "GESPED");
        //PARA QUEM VAI O EMAIL, VC PODE COLOCAR O USUARIO DE CRIACAO,  O QUE ACOMPANHA E O ALTERACO
        if (!novaOrdem) {
            if (ordemNova.getUsuUsuarioByUsuAcompanha() != null) {
                emailOrdem.addTo(ordemNova.getUsuUsuarioByUsuAcompanha().getUsuEmail(),
                        ordemNova.getUsuUsuarioByUsuAcompanha().getUsuUsuario());
                emailOrdem.setSubject("Atribuio de Ordem - Com Acompanhamento");
            } else {
                emailOrdem.addTo(ordemNova.getDepDepartamentoByDepIdDestino().getDepEmail(),
                        ordemNova.getUsuUsuarioByUsuCriacao().getUsuUsuario());
                emailOrdem.setSubject("Atribuio de Ordem - Sem Acompanhamento");
            }
        } else {
            emailOrdem.addTo(ordemNova.getUsuUsuarioByUsuCriacao().getUsuEmail(),
                    ordemNova.getUsuUsuarioByUsuAcompanha().getUsuUsuario());
            emailOrdem.setSubject("Criao de Nova de Ordem");
        }

        emailOrdem.setSocketConnectionTimeout(30000);
        emailOrdem.setSocketTimeout(30000);
        //if (contaPadrao.contains("gmail")) {
        emailOrdem.setSSL(true);
        emailOrdem.setTLS(true);

        //Autenticando no servidor
        emailOrdem.setAuthentication(emailAutenticacao, senhaAutenticacao);
        //Montando o e-mail
        StringBuilder htmlEmail = new StringBuilder();
        htmlEmail.append(
                "<html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\" /> </head><body>");
        htmlEmail.append("<br/>").append("Ol ").append(ordem.getUsuUsuarioByUsuAcompanha().getUsuDescricao())
                .append(",").append("<br/>");
        htmlEmail.append("Uma Ordem Atribuda para seu Usurio:").append("<br/>");
        htmlEmail.append("Protocolo : ").append(ordem.getOrdNumProtocolo()).append("<br/>");
        if (ordem.getOrdPrioridade()) {
            htmlEmail.append("Prioridade : Urgente").append("<br/>");
        } else {
            htmlEmail.append("Prioridade : Normal").append("<br/>");
        }

        htmlEmail.append("\"</body></html>\"");

        //PODE ENVIAR UMA COPIA OCULPA
        emailOrdem.setHtmlMsg(htmlEmail.toString());
        //            List<InternetAddress> copiasOcultas = new ArrayList<>();
        //            copiasOcultas.add(new InternetAddress("enio.a.nunes@gmail.com"));
        //            emailOrdem.setBcc(copiasOcultas);
        emailOrdem.send();

        // context.addMessage(null, new FacesMessage("E-mail enviado com sucesso", this.destino));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:gov.osti.services.Metadata.java

/**
 * Send a NOTIFICATION EMAIL (if configured) when a record is SUBMITTED or
 * ANNOUNCED.// w  w  w  .  java 2 s  . c o m
 *
 * @param md the METADATA in question
 */
private static void sendStatusNotification(DOECodeMetadata md) {
    HtmlEmail email = new HtmlEmail();
    email.setCharset(org.apache.commons.mail.EmailConstants.UTF_8);
    email.setHostName(EMAIL_HOST);

    // if EMAIL or DESTINATION ADDRESS are not set, abort
    if (StringUtils.isEmpty(EMAIL_HOST) || StringUtils.isEmpty(EMAIL_SUBMISSION))
        return;

    // only applicable to SUBMITTED or ANNOUNCED records
    if (!Status.Announced.equals(md.getWorkflowStatus()) && !Status.Submitted.equals(md.getWorkflowStatus()))
        return;

    // get the SITE information
    String siteCode = md.getSiteOwnershipCode();
    Site site = SiteServices.findSiteBySiteCode(siteCode);
    if (null == site) {
        log.warn("Unable to locate SITE information for SITE CODE: " + siteCode);
        return;
    }
    String lab = site.getLab();
    lab = lab.isEmpty() ? siteCode : lab;

    try {
        email.setFrom(EMAIL_FROM);
        email.setSubject("DOE CODE Record " + md.getWorkflowStatus().toString());
        email.addTo(EMAIL_SUBMISSION);

        String softwareTitle = md.getSoftwareTitle().replaceAll("^\\h+|\\h+$", "");

        StringBuilder msg = new StringBuilder();
        msg.append("<html>");
        msg.append("A new DOE CODE record has been ").append(md.getWorkflowStatus()).append(" for ").append(lab)
                .append(" and is awaiting approval:");

        msg.append("<P>Code ID: ").append(md.getCodeId());
        msg.append("<BR>Software Title: ").append(softwareTitle);
        msg.append("</html>");

        email.setHtmlMsg(msg.toString());

        email.send();
    } catch (EmailException e) {
        log.error("Failed to send submission/announcement notification message for #" + md.getCodeId());
        log.error("Message: " + e.getMessage());
    }
}

From source file:gov.osti.services.Metadata.java

/**
 * Send an email notification on APPROVAL of DOE CODE records.
 *
 * @param md the METADATA to send notification for
 *//*from   w w  w.  j a  v  a  2 s  .com*/
private static void sendApprovalNotification(DOECodeMetadata md) {
    HtmlEmail email = new HtmlEmail();
    email.setCharset(org.apache.commons.mail.EmailConstants.UTF_8);
    email.setHostName(EMAIL_HOST);

    // if HOST or record OWNER or PROJECT MANAGER NAME isn't set, cannot send
    if (StringUtils.isEmpty(EMAIL_HOST) || null == md || StringUtils.isEmpty(md.getOwner())
            || StringUtils.isEmpty(PM_NAME))
        return;
    // only has meaning for APPROVED records
    if (!Status.Approved.equals(md.getWorkflowStatus()))
        return;

    try {
        // get the OWNER information
        User owner = UserServices.findUserByEmail(md.getOwner());
        if (null == owner) {
            log.warn("Unable to locate USER information for Code ID: " + md.getCodeId());
            return;
        }

        Long codeId = md.getCodeId();

        // lookup previous Snapshot status info for item
        EntityManager em = DoeServletContextListener.createEntityManager();
        TypedQuery<MetadataSnapshot> querySnapshot = em
                .createNamedQuery("MetadataSnapshot.findByCodeIdLastNotStatus", MetadataSnapshot.class)
                .setParameter("status", DOECodeMetadata.Status.Approved).setParameter("codeId", codeId);

        String lastApprovalFor = "submitted/announced";
        List<MetadataSnapshot> results = querySnapshot.setMaxResults(1).getResultList();
        for (MetadataSnapshot ms : results) {
            lastApprovalFor = ms.getSnapshotKey().getSnapshotStatus().toString().toLowerCase();
        }

        String softwareTitle = md.getSoftwareTitle().replaceAll("^\\h+|\\h+$", "");

        email.setFrom(EMAIL_FROM);
        email.setSubject("Approved -- DOE CODE ID: " + codeId + ", " + softwareTitle);
        email.addTo(md.getOwner());

        // if email is provided, BCC the Project Manager
        if (!StringUtils.isEmpty(PM_EMAIL))
            email.addBcc(PM_EMAIL, PM_NAME);

        StringBuilder msg = new StringBuilder();

        msg.append("<html>");
        msg.append("Dear ").append(owner.getFirstName()).append(" ").append(owner.getLastName()).append(":");

        msg.append("<P>Thank you -- your ").append(lastApprovalFor).append(" project, DOE CODE ID: <a href=\"")
                .append(SITE_URL).append("/biblio/").append(codeId).append("\">").append(codeId)
                .append("</a>, has been approved.  It is now <a href=\"").append(SITE_URL)
                .append("\">searchable</a> in DOE CODE by, for example, title or CODE ID #.</P>");

        // OMIT the following for BUSINESS TYPE software, or last ANNOUNCED software
        if (!DOECodeMetadata.Type.B.equals(md.getSoftwareType())
                && !lastApprovalFor.equalsIgnoreCase("announced")) {
            msg.append(
                    "<P>You may need to continue editing your project to announce it to the Department of Energy ")
                    .append("to ensure announcement and dissemination in accordance with DOE statutory responsibilities. For more information please see ")
                    .append("<a href=\"").append(SITE_URL)
                    .append("/faq#what-does-it-mean-to-announce\">What does it mean to announce scientific code to DOE CODE?</a></P>");
        }
        msg.append(
                "<P>If you have questions such as What are the benefits of getting a DOI for code or software?, see the ")
                .append("<a href=\"").append(SITE_URL).append("/faq\">DOE CODE FAQs</a>.</P>");
        msg.append(
                "<P>If we can be of assistance, please do not hesitate to <a href=\"mailto:doecode@osti.gov\">Contact Us</a>.</P>");
        msg.append("<P>Sincerely,</P>");
        msg.append("<P>").append(PM_NAME).append("<BR/>Product Manager for DOE CODE<BR/>USDOE/OSTI</P>");

        msg.append("</html>");

        email.setHtmlMsg(msg.toString());

        email.send();
    } catch (EmailException e) {
        log.error("Unable to send APPROVAL notification for #" + md.getCodeId());
        log.error("Message: " + e.getMessage());
    }
}