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

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

Introduction

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

Prototype

public void setAuthentication(final String userName, final String password) 

Source Link

Document

Sets the userName and password if authentication is needed.

Usage

From source file:bean.OrdemBean.java

private void enviarEmailOrdem(OrdOrdem ordemNova, boolean novaOrdem) {
    try {/*from  www.j a va 2 s .  c  o m*/
        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:org.infoglue.cms.util.mail.MailService.java

/**
 *
 * @param from the sender of the email.//from  w  w w .  j  a  va2s  .  c o m
 * @param to the recipient of the email.
 * @param subject the subject of the email.
 * @param content the body of the email.
 * @throws SystemException if the email couldn't be sent due to some mail server exception.
 */
public void sendHTML(String from, String to, String cc, String bcc, String bounceAddress, String replyTo,
        String subject, String content, String encoding) throws SystemException {
    try {
        HtmlEmail email = new HtmlEmail();
        String mailServer = CmsPropertyHandler.getMailSmtpHost();
        String mailPort = CmsPropertyHandler.getMailSmtpPort();
        String systemEmailSender = CmsPropertyHandler.getSystemEmailSender();

        email.setHostName(mailServer);
        if (mailPort != null && !mailPort.equals(""))
            email.setSmtpPort(Integer.parseInt(mailPort));

        boolean needsAuthentication = false;
        try {
            needsAuthentication = new Boolean(CmsPropertyHandler.getMailSmtpAuth()).booleanValue();
        } catch (Exception ex) {
            needsAuthentication = false;
        }

        if (needsAuthentication) {
            final String userName = CmsPropertyHandler.getMailSmtpUser();
            final String password = CmsPropertyHandler.getMailSmtpPassword();

            email.setAuthentication(userName, password);
        }

        email.setBounceAddress(systemEmailSender);
        email.setCharset(encoding);

        if (logger.isInfoEnabled()) {
            logger.info("systemEmailSender:" + systemEmailSender);
            logger.info("to:" + to);
            logger.info("from:" + from);
            logger.info("mailServer:" + mailServer);
            logger.info("mailPort:" + mailPort);
            logger.info("cc:" + cc);
            logger.info("bcc:" + bcc);
            logger.info("replyTo:" + replyTo);
            logger.info("subject:" + subject);
        }

        if (to.indexOf(";") > -1) {
            cc = to;
            to = from;
        }

        String limitString = CmsPropertyHandler.getEmailRecipientLimit();
        if (limitString != null && !limitString.equals("-1")) {
            try {
                Integer limit = new Integer(limitString);
                int count = 0;
                if (cc != null)
                    count = count + cc.split(";").length;
                if (bcc != null)
                    count = count + bcc.split(";").length;

                logger.info("limit: " + limit + ", count: " + count);
                if (count > limit)
                    throw new Exception("You are not allowed to send mail to more than " + limit
                            + " recipients at a time. This is specified in app settings.");
            } catch (NumberFormatException e) {
                logger.error("Exception validating number of recipients in mailservice:" + e.getMessage(), e);
            }
        }

        email.addTo(to, to);
        email.setFrom(from, from);
        if (cc != null)
            email.setCc(createInternetAddressesList(cc));
        if (bcc != null)
            email.setBcc(createInternetAddressesList(bcc));
        if (replyTo != null)
            email.setReplyTo(createInternetAddressesList(replyTo));

        email.setSubject(subject);

        email.setHtmlMsg(content);

        email.setTextMsg("Your email client does not support HTML messages");

        email.send();

        logger.info("Email sent!");
    } catch (Exception e) {
        logger.error("An error occurred when we tried to send this mail:" + e.getMessage(), e);
        throw new SystemException("An error occurred when we tried to send this mail:" + e.getMessage(), e);
    }
}

From source file:org.jcronjob.service.NoticeService.java

public void sendMessage(Long receiverId, Long workId, String emailAddress, String mobiles, String content) {
    try {/* ww  w  .j av a 2s .com*/
        HtmlEmail email = new HtmlEmail();
        email.setCharset("UTF-8");
        email.setHostName(config.getSmtpHost());
        email.setSslSmtpPort(config.getSmtpPort().toString());
        email.setAuthentication(config.getSenderEmail(), config.getPassword());
        email.setFrom(config.getSenderEmail());
        email.setSubject("cronjob");
        email.setHtmlMsg(msgToHtml(receiverId, content));
        email.addTo(emailAddress.split(","));
        email.send();

        Log log = new Log();
        log.setType(0);
        log.setWorkerId(workId);
        log.setMessage(content);
        for (String receiver : emailAddress.split(",")) {
            log.setReceiver(receiver);
            log.setSendTime(new Date());
            homeService.saveLog(log);
        }
        log.setType(1);
        for (String mobile : mobiles.split(",")) {
            //??POST
            String sendUrl = String.format(config.getSendUrl(), mobile,
                    String.format(config.getTemplate(), content));

            String url = sendUrl.substring(0, sendUrl.indexOf("?"));
            String postData = sendUrl.substring(sendUrl.indexOf("?") + 1);

            String message = HttpUtils.doPost(url, postData, "UTF-8");
            log.setReceiver(mobile);
            log.setResult(message);
            log.setSendTime(new Date());
            homeService.saveLog(log);
            logger.info(message);

        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

}

From source file:org.meerkat.network.MailManager.java

/**
 * sendEmail//from  w w w .j  a va 2 s.  c  om
 * @param subject
 * @param message
 */
public final void sendEmail(String subject, String message) {
    this.refreshSettings();

    HtmlEmail email = new HtmlEmail();
    email.setHostName(getSMTPServer());
    email.setSmtpPort(Integer.valueOf(getSMTPPort()));
    email.setSubject(subject);
    try {
        email.setHtmlMsg(message);
    } catch (EmailException e2) {
        log.error("Error in mail message. ", e2);
    }

    // SMTP security
    String security = getSMTPSecurity();
    if (security.equalsIgnoreCase("STARTTLS")) {
        email.setTLS(true);
    } else if (security.equalsIgnoreCase("SSL/TLS")) {
        email.setSSL(true);
        email.setSslSmtpPort(String.valueOf(getSMTPPort()));
    }
    email.setAuthentication(getSMTPUser(), getSMTPPassword());

    try {
        String[] toList = getTO().split(",");
        for (int i = 0; i < toList.length; i++) {
            email.addTo(toList[i].trim());
        }

    } catch (EmailException e1) {
        log.error("EmailException: addTo(" + getTO() + "). " + e1.getMessage());
    }

    try {
        email.setFrom(getFROM());
    } catch (EmailException e1) {
        log.error("EmailException: setFrom(" + getFROM() + "). " + e1.getMessage());
    }

    // Send the email
    try {
        email.send();
    } catch (EmailException e) {
        log.error("Failed to send email!", e);
    }
}

From source file:org.meerkat.network.MailManager.java

/**
 * testEmailSettingsFromWebService/*from   w ww.java  2s.  co  m*/
 * @param from
 * @param to
 * @param smtpServer
 * @param smtpPort
 * @param smtpSecurity
 * @param smtpUser
 * @param smtpPassword
 * @return
 */
public final String sendTestEmailSettingsFromWebService(String from, String to, String smtpServer,
        String smtpPort, String smtpSecurity, String smtpUser, String smtpPassword) {
    String resultString = "OK";
    HtmlEmail email = new HtmlEmail();
    email.setHostName(smtpServer);
    email.setSmtpPort(Integer.valueOf(smtpPort));
    email.setSubject(testSubject);
    try {
        email.setHtmlMsg(testMessage);
    } catch (EmailException e2) {
        resultString = e2.getMessage();
        return resultString;
    }

    // SMTP security
    if (smtpSecurity.equalsIgnoreCase("STARTTLS")) {
        email.setTLS(true);
    } else if (smtpSecurity.equalsIgnoreCase("SSLTLS")) {
        email.setSSL(true);
        email.setSslSmtpPort(String.valueOf(smtpPort));
    }
    email.setAuthentication(smtpUser, smtpPassword);

    try {
        String[] toList = to.split(",");
        for (int i = 0; i < toList.length; i++) {
            email.addTo(toList[i].trim());
        }

    } catch (EmailException e1) {
        resultString = "TO: " + e1.getMessage();
        return resultString;
    }

    try {
        email.setFrom(from);
    } catch (EmailException e1) {
        resultString = "FROM: " + e1.getMessage();
        return resultString;
    }

    // Send the email
    try {
        email.send();
    } catch (EmailException e) {
        resultString = e.getMessage();
        return resultString;
    }

    return resultString;
}

From source file:org.opencron.server.service.NoticeService.java

public void sendMessage(List<User> users, Long workId, String emailAddress, String mobiles, String content) {
    Log log = new Log();
    log.setIsread(false);/*  ww  w  .  j  a  va  2 s.c om*/
    log.setAgentId(workId);
    log.setMessage(content);
    //???
    if (CommonUtils.isEmpty(emailAddress, mobiles)) {
        log.setType(Opencron.MsgType.WEBSITE.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
        return;
    }

    /**
     * ????
     */
    boolean emailSuccess = false;
    boolean mobileSuccess = false;

    Config config = configService.getSysConfig();
    try {
        log.setType(Opencron.MsgType.EMAIL.getValue());
        HtmlEmail email = new HtmlEmail();
        email.setCharset("UTF-8");
        email.setHostName(config.getSmtpHost());
        email.setSslSmtpPort(config.getSmtpPort().toString());
        email.setAuthentication(config.getSenderEmail(), config.getPassword());
        email.setFrom(config.getSenderEmail());
        email.setSubject("opencron");
        email.setHtmlMsg(msgToHtml(content));
        email.addTo(emailAddress.split(","));
        email.send();
        emailSuccess = true;
        /**
         * ??
         */
        log.setReceiver(emailAddress);
        log.setSendTime(new Date());
        homeService.saveLog(log);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    /**
     * ????
     */
    try {
        for (String mobile : mobiles.split(",")) {
            //??POST
            String sendUrl = String.format(config.getSendUrl(), mobile,
                    String.format(config.getTemplate(), content));
            String url = sendUrl.substring(0, sendUrl.indexOf("?"));
            String postData = sendUrl.substring(sendUrl.indexOf("?") + 1);
            String message = HttpUtils.doPost(url, postData, "UTF-8");
            log.setResult(message);
            logger.info(message);
            mobileSuccess = true;
        }
        log.setReceiver(mobiles);
        log.setType(Opencron.MsgType.SMS.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    /**
     * ??,??
     */
    if (!mobileSuccess && !emailSuccess) {
        log.setType(Opencron.MsgType.WEBSITE.getValue());
        log.setSendTime(new Date());
        for (User user : users) {
            //??
            log.setUserId(user.getUserId());
            log.setReceiver(user.getUserName());
            homeService.saveLog(log);
        }
    }

}

From source file:org.oscarehr.oscar_apps.util.Log4JGmailExecutorTask.java

private void sendEmail() throws EmailException {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(smtpServer);/*  ww w .j  a  v  a2  s. co m*/
    if (smtpUser != null && smtpPassword != null)
        email.setAuthentication(smtpUser, smtpPassword);

    if (smtpSslPort != null) {
        email.setSSL(true);
        email.setSslSmtpPort(smtpSslPort);
    }

    Session session = email.getMailSession();
    Properties properties = session.getProperties();
    properties.setProperty("mail.smtp.connectiontimeout", "20000");
    properties.setProperty("mail.smtp.timeout", "20000");

    email.addTo(recipientEmailAddress, recipientEmailAddress);
    email.setFrom(smtpUser, smtpUser);

    email.setSubject(subject);
    email.setHtmlMsg(contents);
    email.setTextMsg(contents);
    email.send();
}

From source file:org.oscarehr.util.EmailUtils.java

/**
 * This method will return an HtmlEmail object populated with 
 * the values passed in, ignoring the parameters in the configuration file.
 *//*from  w  ww .  java2  s  .c  om*/
public static HtmlEmail getHtmlEmail(String smtpServer, String smtpPort, String smtpUser, String smtpPassword,
        String connectionSecurity) throws EmailException {
    logger.debug("smtpServer=" + smtpServer + ", smtpSslPort=" + smtpPort + ", smtpUser=" + smtpUser
            + ", smtpPassword=" + smtpPassword + ",connectionSecurity=" + connectionSecurity);

    HtmlEmail email = null;

    if (RECIPIENT_OVERRIDE_KEY != null || printInsteadOfSend)
        email = new HtmlEmailWrapper();
    else
        email = new HtmlEmail();

    email.setHostName(smtpServer);

    if (smtpUser != null && smtpPassword != null)
        email.setAuthentication(smtpUser, smtpPassword);

    Session session = email.getMailSession();

    if (connectionSecurity != null) {
        if (connectionSecurity.equals(CONNECTION_SECURITY_STARTTLS)) {
            session.getProperties().setProperty(Email.MAIL_TRANSPORT_TLS, "true");
            email.setTLS(true);
        } else if (connectionSecurity.equals(CONNECTION_SECURITY_SSL)) {
            email.setSSL(true);
        }
    }

    if (smtpPort != null) {
        email.setSslSmtpPort(smtpPort);
    }

    Properties properties = session.getProperties();
    properties.setProperty("mail.smtp.connectiontimeout", "20000");
    properties.setProperty("mail.smtp.timeout", "20000");

    return (email);
}

From source file:org.teknux.dropbitz.service.email.EmailSender.java

public void sendEmail(DropbitzEmail dropbitzEmail, HtmlEmail email) throws EmailServiceException {
    logger.debug("Send email...");

    if (dropbitzEmail == null) {
        throw new EmailServiceException("DropbitzEmail can not be null");
    }//from ww  w  .j a v a 2s  . c  o m
    if (email == null) {
        throw new EmailServiceException("HtmlEmail can not be null");
    }

    //Global Configuration
    email.setHostName(Objects.requireNonNull(config.getEmailHost(), "Email Host is required"));
    email.setSmtpPort(config.getEmailPort());
    if ((config.getEmailUsername() != null && !config.getEmailUsername().isEmpty())
            || (config.getEmailPassword() != null && !config.getEmailPassword().isEmpty())) {
        email.setAuthentication(config.getEmailUsername(), config.getEmailPassword());
    }
    email.setSSLOnConnect(config.isEmailSsl());

    email.setSubject(dropbitzEmail.getSubject());
    try {
        email.setFrom(Objects.requireNonNull(dropbitzEmail.getEmailFrom(), "Email From is required"));
        if (dropbitzEmail.getEmailTo() == null || dropbitzEmail.getEmailTo().size() == 0) {
            throw new EmailServiceException("Email To is required");
        }
        email.addTo(dropbitzEmail.getEmailTo().toArray(new String[dropbitzEmail.getEmailTo().size()]));
        email.setHtmlMsg(Objects.requireNonNull(dropbitzEmail.getHtmlMsg(), "HtmlMsg is required"));
        if (dropbitzEmail.getTextMsg() != null) {
            email.setTextMsg(dropbitzEmail.getTextMsg());
        }
        email.send();

        logger.trace(MessageFormat.format("Email sent from [{0}] to [{1}]", dropbitzEmail.getEmailFrom(),
                String.join(",", dropbitzEmail.getEmailTo())));
    } catch (EmailException e) {
        throw new EmailServiceException("Email not sent", e);
    }
}

From source file:org.vulpe.commons.util.VulpeEmailUtil.java

/**
 * Send Mail to many recipients.// ww  w  . j a va  2  s .  com
 *
 * @param recipients
 *            Recipients
 * @param subject
 *            Subject
 * @param body
 *            Body
 * @throws VulpeSystemException
 *             exception
 */
public static boolean sendMail(final String[] recipients, final String subject, final String body) {
    boolean sended = true;
    if (!checkValidEmail(recipients)) {
        LOG.error("Invalid mails: " + recipients);
        sended = false;
    }
    if (isDebugEnabled) {
        LOG.debug("Entering in sendMail...");
        for (int i = 0; i < recipients.length; i++) {
            LOG.debug("recipient: " + recipients[i]);
        }
        LOG.debug("subject: " + subject);
        LOG.debug("body: " + body);
    }
    try {
        final ResourceBundle bundle = ResourceBundle.getBundle("mail");
        if (bundle != null) {
            final HtmlEmail mail = new HtmlEmail();
            String mailFrom = "";
            if (bundle.containsKey("mail.smtp.auth") && Boolean.valueOf(bundle.getString("mail.smtp.auth"))) {
                final String username = bundle.getString("mail.smtp.user");
                final String password = bundle.getString("mail.smtp.password");
                mail.setAuthentication(username, password);
            }
            if (bundle.containsKey("mail.from")) {
                mailFrom = bundle.getString("mail.from");
            }
            mail.setFrom(mailFrom);
            for (final String recipient : recipients) {
                mail.addTo(recipient);
            }
            mail.setHostName(bundle.getString("mail.smtp.host"));
            final String port = bundle.getString("mail.smtp.port");
            mail.setSmtpPort(Integer.valueOf(port));
            if (bundle.containsKey("mail.smtp.starttls.enable")
                    && Boolean.valueOf(bundle.getString("mail.smtp.starttls.enable"))) {
                mail.setTLS(true);
                mail.setSSL(true);
                if (bundle.containsKey("mail.smtp.socketFactory.port")) {
                    String factoryPort = bundle.getString("mail.smtp.socketFactory.port");
                    mail.setSslSmtpPort(factoryPort);
                }
            }
            String encoding = "UTF-8";
            if (bundle.containsKey("mail.encode")) {
                encoding = bundle.getString("mail.encode");
            }
            mail.setCharset(encoding);
            mail.setSubject(subject);
            mail.setHtmlMsg(body);
            mail.send();
        } else {
            LOG.error("Send Mail properties not setted");
            sended = false;
        }
    } catch (Exception e) {
        LOG.error("Error on send mail", e);
        sended = false;
    }
    LOG.debug("Out of sendMail...");
    return sended;
}