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

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

Introduction

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

Prototype

public void setSmtpPort(final int aPortNumber) 

Source Link

Document

Set the port number of the outgoing mail server.

Usage

From source file:br.com.atmatech.sac.controller.Email.java

public void emailAtendimento(String smtp, String user, String password, Integer porta, Boolean ssl, Boolean tls,
        String emailto, String emailfrom, String solicitante, String nchamado, String razao, String data,
        String solicitacao, String realizacao, String tecnico, String imagem)
        throws EmailException, MalformedURLException {
    System.err.println(smtp + ":\n" + user + ":\n" + password + ":\n" + porta + ":\n" + ssl + ":\n" + tls
            + ":\n" + emailto + ":\n" + emailfrom + ":\n" + solicitante + ":\n" + nchamado + ":\n" + razao
            + ":\n" + data + ":\n" + solicitacao + ":\n" + realizacao + ":\n" + tecnico + ":\n" + imagem);
    HtmlEmail email = new HtmlEmail();
    // SimpleEmail email = new SimpleEmail();
    email.setHostName(smtp); // o servidor SMTP para envio do e-mail
    email.addTo(emailto); //destinatrio
    email.setFrom(emailfrom); // remetente        
    email.setSubject("Aviso de Atendimento - Suporte");
    // configura a mensagem para o formato HTML        
    email.setHtmlMsg(/*from  ww w  . j av a2 s  .com*/
            "<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">Prezado(a)Senhor(a).<br>"
                    + "<b>" + solicitante + "</b><p>" + "Informamos que o protocolo nmero&#013<b> " + nchamado
                    + "</b> foi finalizado por nossa Central de Suporte.<p>" + "Cliente<br>" + "" + razao
                    + "<p>" + "Data<br>" + "" + data + "<p>" + "Descrio do Problema<br>" + "" + solicitacao
                    + "<p>" + "Soluo<br>" + "" + realizacao + "<p>" + "Atendente<br>" + "" + tecnico + "<p>"
                    + "<b>Atenciosamente</b> Suporte Atmatech<p><p>" + imagem + " </html>");
    //email.setMsg("Teste");
    email.setAuthentication(user, password);
    email.setSmtpPort(porta);
    email.setSSL(ssl);
    email.setTLS(tls);
    email.send();
}

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;/*from   w  w w  .  j a  v a2s  . co  m*/
    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:Email.CommonsEmail.java

/**
 * Envia email no formato HTML/* ww w .jav a2 s . co  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:bean.OrdemBean.java

private void enviarEmailOrdem(OrdOrdem ordemNova, boolean novaOrdem) {
    try {//from   w  w  w  .j a v  a 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:net.wildpark.dswp.supports.MailService.java

public boolean sendEmail(String to, String textBody) {
    try {// ww  w  . java  2s .  co m
        HtmlEmail email = new HtmlEmail();
        email.setCharset("utf-8");
        email.setHostName("mail.wildpark.net");
        email.setSmtpPort(25);
        email.setAuthenticator(new DefaultAuthenticator("informer@mksat.net", "22v5C728"));
        email.setFrom("informer@mksat.net");
        email.setSubject("Automatic message from darkside.wildpark.net");
        email.setHtmlMsg(textBody);
        email.addTo(to);
        email.send();
        logFacade.create(new Log("Sended mail " + to));
    } catch (EmailException ex) {
        logFacade.create(new Log("Error with mail sending", ex, LoggerLevel.ERROR));
        System.out.println(ex);
        return false;
    }
    return true;
}

From source file:org.apache.unomi.plugins.mail.actions.SendMailAction.java

public int execute(Action action, Event event) {
    String from = (String) action.getParameterValues().get("from");
    String to = (String) action.getParameterValues().get("to");
    String cc = (String) action.getParameterValues().get("cc");
    String bcc = (String) action.getParameterValues().get("bcc");
    String subject = (String) action.getParameterValues().get("subject");
    String template = (String) action.getParameterValues().get("template");

    ST stringTemplate = new ST(template);
    stringTemplate.add("profile", event.getProfile());
    stringTemplate.add("event", event);
    // load your HTML email template
    String htmlEmailTemplate = stringTemplate.render();

    // define you base URL to resolve relative resource locations
    try {//w  ww.jav  a  2s  . com
        new URL("http://www.apache.org");
    } catch (MalformedURLException e) {
        //
    }

    // create the email message
    HtmlEmail email = new ImageHtmlEmail();
    // email.setDataSourceResolver(new DataSourceResolverImpl(url));
    email.setHostName(mailServerHostName);
    email.setSmtpPort(mailServerPort);
    email.setAuthenticator(new DefaultAuthenticator(mailServerUsername, mailServerPassword));
    email.setSSLOnConnect(mailServerSSLOnConnect);
    try {
        email.addTo(to);
        email.setFrom(from);
        if (cc != null && cc.length() > 0) {
            email.addCc(cc);
        }
        if (bcc != null && bcc.length() > 0) {
            email.addBcc(bcc);
        }
        email.setSubject(subject);

        // set the html message
        email.setHtmlMsg(htmlEmailTemplate);

        // set the alternative message
        email.setTextMsg("Your email client does not support HTML messages");

        // send the email
        email.send();
    } catch (EmailException e) {
        logger.error("Cannot send mail", e);
    }

    return EventService.NO_CHANGE;
}

From source file:org.cerberus.service.email.impl.sendMail.java

public static void sendHtmlMail(String host, int port, String body, String subject, String from, String to,
        String cc) throws Exception {

    HtmlEmail email = new HtmlEmail();
    email.setSmtpPort(port);
    email.setDebug(false);/*from  www.  j av  a  2  s .  c om*/
    email.setHostName(host);
    email.setFrom(from);
    email.setSubject(subject);
    email.setHtmlMsg(body);

    String[] destinataire = to.split(";");

    for (int i = 0; i < destinataire.length; i++) {
        String name;
        String emailaddress;
        if (destinataire[i].contains("<")) {
            String[] destinatairedata = destinataire[i].split("<");
            name = destinatairedata[0].trim();
            emailaddress = destinatairedata[1].replace(">", "").trim();
        } else {
            name = "";
            emailaddress = destinataire[i];
        }
        email.addTo(emailaddress, name);
    }

    String[] copy = cc.split(";");

    for (int i = 0; i < copy.length; i++) {
        String namecc;
        String emailaddresscc;
        if (copy[i].contains("<")) {
            String[] copydata = copy[i].split("<");
            namecc = copydata[0].trim();
            emailaddresscc = copydata[1].replace(">", "").trim();
        } else {
            namecc = "";
            emailaddresscc = copy[i];
        }
        email.addCc(emailaddresscc, namecc);
    }

    email.setTLS(true);

    email.send();

}

From source file:org.infoglue.cms.util.mail.MailService.java

/**
 *
 * @param from the sender of the email.//from  w w w  . j  a v a 2 s. com
 * @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.jevis.jealarm.AlarmHandler.java

/**
 * Send the Alarm mail/*from   ww  w. j a v a  2 s  . c  o m*/
 *
 * @param conf
 * @param alarm
 * @param body
 */
public void sendAlarm(Config conf, Alarm alarm, String body) {
    try {
        HtmlEmail email = new HtmlEmail();

        //            Email email = new SimpleEmail();
        email.setHostName(conf.getSmtpServer());
        email.setSmtpPort(conf.getSmtpPort());
        email.setAuthenticator(new DefaultAuthenticator(conf.getSmtpUser(), conf.getSmtpPW()));
        email.setSSLOnConnect(conf.isSmtpSSL());
        email.setFrom(conf.smtpFrom);
        email.setSubject(alarm.getSubject());

        for (String recipient : alarm.getRecipient()) {
            email.addTo(recipient);
        }

        for (String bcc : alarm.getBcc()) {
            email.addBcc(bcc);
        }
        email.setHtmlMsg(body);

        email.send();
        System.out.println("Alarm send: " + alarm.getSubject());
    } catch (Exception ex) {
        System.out.println("cound not send Email");
        ex.printStackTrace();
    }

}

From source file:org.jkandasa.email.blaster.EmailUtils.java

public static HtmlEmail initializeEmail(AppProperties appProperties) throws EmailException {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(appProperties.getSmtpHost());
    email.setSmtpPort(Integer.valueOf(appProperties.getSmtpPort()));
    if (appProperties.getUsername() != null && appProperties.getUsername().length() > 0) {
        email.setAuthenticator(//from w  w  w.  jav a2 s. c  o m
                new DefaultAuthenticator(appProperties.getUsername(), appProperties.getPassword()));
    }
    email.setSSLOnConnect(appProperties.isEnableSSL());
    email.setFrom(appProperties.getFromAddress());
    return email;
}