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

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

Introduction

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

Prototype

public String send() throws EmailException 

Source Link

Document

Sends the email.

Usage

From source file:br.com.itfox.beans.SendHtmlFormatedEmail.java

public void sendingHtml() {
    try {/*  w w w.  j av a2  s .  c  o  m*/
        // Create the email message
        HtmlEmail email = new HtmlEmail();
        email.setHostName("mail.congressotrt15.com.br");
        email.setSmtpPort(587);
        email.setAuthenticator(new DefaultAuthenticator("congresso@congressotrt15.com.br", "admtrt15xx"));
        email.setSSLOnConnect(false);
        //email.setTLS(true);
        email.setFrom("congresso@congressotrt15.com.br");
        email.setSubject("TestMail");
        email.addTo("belchiorpalma@gmail.com", "Belchior Palma");
        //email.setFrom("belchiorpalma@me.com", "Me");
        email.setSubject("Test email with inline image");
        email.setSubject(MimeUtility.encodeText("Test email with inline image", "UTF-8", "B"));

        // embed the image and get the content id
        URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
        String cid = email.embed(url, "Apache logo");

        // set the html message
        email.setHtmlMsg("<html>The apache logo - <img src=\"cid:" + cid + "\"></html>");

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

        // send the email
        email.send();
    } catch (EmailException ex) {
        Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MalformedURLException ex) {
        Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:de.maklerpoint.office.Schnittstellen.Email.MultiEmailSender.java

public void send() throws EmailException {

    if (files != null && urls != null) {
        attachments = new EmailAttachment[files.length + urls.length];

        int cnt = 0;

        for (int i = 0; i < files.length; i++) {
            attachments[cnt] = new EmailAttachment();
            attachments[cnt].setPath(files[i].getPath());
            attachments[cnt].setName(files[i].getName());
            attachments[cnt].setDisposition(EmailAttachment.ATTACHMENT);

            cnt++;//from   www . j av  a 2s.  c o  m
        }

        for (int i = 0; i < urls.length; i++) {
            attachments[cnt] = new EmailAttachment();
            attachments[cnt].setURL(urls[i]);
            attachments[cnt].setName(urls[i].getFile());
            attachments[cnt].setDisposition(EmailAttachment.ATTACHMENT);
            cnt++;
        }

    } else if (files != null) {
        attachments = new EmailAttachment[files.length];

        for (int i = 0; i < files.length; i++) {
            attachments[i] = new EmailAttachment();
            attachments[i].setPath(files[i].getPath());
            attachments[i].setName(files[i].getName());
            attachments[i].setDisposition(EmailAttachment.ATTACHMENT);
        }
    } else if (urls != null) {
        attachments = new EmailAttachment[urls.length];

        for (int i = 0; i < urls.length; i++) {
            attachments[i] = new EmailAttachment();
            attachments[i].setURL(urls[i]);
            attachments[i].setName(urls[i].getFile());
            attachments[i].setDisposition(EmailAttachment.ATTACHMENT);
        }
    }

    HtmlEmail email = new HtmlEmail();
    email.setHostName(Config.get("mailHost", ""));
    email.setSmtpPort(Config.getConfigInt("mailPort", 25));

    email.setTLS(Config.getConfigBoolean("mailTLS", false));
    email.setSSL(Config.getConfigBoolean("mailSSL", false));

    //email.setSslSmtpPort(Config.getConfigInt("emailPort", 25));
    email.setAuthenticator(
            new DefaultAuthenticator(Config.get("mailUsername", ""), Config.get("mailPassword", "")));

    email.setFrom(Config.get("mailSendermail", "info@example.de"), Config.get("mailSender", null));

    email.setSubject(subject);
    email.setHtmlMsg(body);
    email.setTextMsg(nohtmlmsg);

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

    if (cc != null) {
        for (int i = 0; i < cc.length; i++) {
            email.addCc(cc[i]);
        }
    }

    if (attachments != null) {
        for (int i = 0; i < attachments.length; i++) {
            email.attach(attachments[i]);
        }
    }

    email.send();

}

From source file:de.hybris.platform.acceleratorservices.email.impl.DefaultEmailServiceTest.java

@Test
public void testSendWithAttachments() {
    final EmailAddressModel toAddress = mock(EmailAddressModel.class);
    final EmailAddressModel fromAddress = mock(EmailAddressModel.class);
    final EmailMessageModel emailMessageModel = mock(EmailMessageModel.class);
    final HtmlEmail email = mock(HtmlEmail.class);
    given(emailMessageModel.getToAddresses()).willReturn(Collections.singletonList(toAddress));
    given(emailMessageModel.getFromAddress()).willReturn(fromAddress);
    given(toAddress.getEmailAddress()).willReturn("ramana@neoworks.com");
    given(toAddress.getDisplayName()).willReturn("ramana ulluri");
    given(fromAddress.getEmailAddress()).willReturn("customerservices@hybris.com");
    given(fromAddress.getDisplayName()).willReturn("Customer Services");
    given(emailMessageModel.getSubject()).willReturn("subject - test");
    given(emailMessageModel.getBody()).willReturn(
            "body - This is a test email with dummy attachment from CommerceServices.DefaultEmailServiceTest.testSendWithAttachments()");

    final EmailAttachmentModel attachment = mock(EmailAttachmentModel.class);
    given(mediaService.getDataFromMedia(attachment)).willReturn(new byte[] {});
    given(emailMessageModel.getAttachments()).willReturn(Collections.singletonList(attachment));
    given(attachment.getMime()).willReturn("image/jpeg");
    given(attachment.getRealFileName()).willReturn("test");

    try {/*from w w w . j av  a 2s  .co m*/
        when(email.send()).thenReturn("messageId");
    } catch (final EmailException e) {
        Assert.fail("EmailException was thrown");
    }

    final boolean result = emailService.send(emailMessageModel);

    verify(attachment, times(1)).getMime();
    verify(modelService, times(1)).save(emailMessageModel);

    Assert.assertTrue(result);
}

From source file:com.ipc.service.SignUpService.java

public String sendpwmail(int uid, String key, String email) throws IOException, EmailException {
    System.out.println("Email : " + email);
    HtmlEmail sendemail = new HtmlEmail();
    sendemail.setCharset("euc-kr");
    sendemail.setHostName("smtp.worksmobile.com");
    sendemail.addTo(email);/*  www .  ja  va2  s.  c  o  m*/
    sendemail.setFrom("jinuk@ideaconcert.com", "");
    sendemail.setSubject("?  .");
    sendemail.setAuthentication("jinuk@ideaconcert.com", "tpxmapsb1");
    sendemail.setSmtpPort(465);
    sendemail.setSSL(true); //?
    sendemail.setTLS(true);
    sendemail.setDebug(true);
    String htmlmsg = "<html><div style='width:1000px; float:left; border-bottom:2px solid #45d4fe; padding-bottom:5px;box-sizing:border-box;'></div><div style='width:1000px;float:left; box-sizing:border-box; padding:15px;'><h2>?   .</h2><div style='width:100%; float:left; box-sizing:border-box; border:5px solid #f9f9f9; text-align:center; padding:40px 0 40px 0;'><span>  ?  <br> .<br>"
            + key + "</span></html>";
    System.out.println(htmlmsg);
    sendemail.setHtmlMsg(htmlmsg);
    try {
        sendemail.send();
    } catch (Exception e) {
        System.out.println("NOTOK");
        return "NOTOK";
    }
    return "OK";
}

From source file:Email.CommonsEmail.java

/**
 * funo para enviar email//  ww w.j a  v  a2s.c o  m
 *
 * @param titulo
 * @param msgEmail
 * @param emailDestinatarios
 * @return
 */
public boolean enviarEmail(String titulo, String msgEmail, String emailDestinatarios) {
    boolean enviado = false;
    String para = emailDestinatarios.toLowerCase().trim();
    String subject = titulo.trim();
    String msg = msgEmail.trim();

    try {
        StringTokenizer stPara = new StringTokenizer(para, ";");

        while (stPara.hasMoreTokens()) {
            if (!stPara.toString().trim().equals("")) {
                HtmlEmail email = new HtmlEmail();
                /*o servidor SMTP para envio do e-mail*/
                email.setHostName(emailConfig.getHostname());
                email.setSmtpPort(emailConfig.getPorta());
                email.setSSLOnConnect(emailConfig.getSsl());
                email.setStartTLSEnabled(emailConfig.getTsl());

                /*remetente*/
                email.setFrom(emailConfig.getEmail(), emailConfig.getNome());
                email.setAuthentication(emailConfig.getUsuario(), emailConfig.getSenha());
                /* ---------------------------------------------------------- */
                //destinatrio
                //email.addTo(emailDestinatario, nomeDestinatario);
                email.addTo(stPara.nextToken().trim());
                // assunto do e-mail
                email.setSubject(subject);

                //conteudo do e-mail
                //configura a mensagem para o formato HTML
                email.setHtmlMsg(msg);
                // configure uma mensagem alternativa caso o servidor no suporte HTML
                email.setTextMsg("Seu servidor de e-mail no suporta mensagem HTML");

                // envia email
                email.send();
                enviado = true;
            }
        }
    } catch (EmailException ex) {
        enviado = false;
        Logger.getLogger(CommonsEmail.class.getName()).log(Level.SEVERE, null, ex);
    }
    return enviado;
}

From source file:com.duroty.service.Mailet.java

/**
 * DOCUMENT ME!//w w w.  j  a v  a 2s.c om
 *
 * @param username DOCUMENT ME!
 * @param to DOCUMENT ME!
 */
private void sendVacationMessage(String username, String to) {
    SessionFactory hfactory = null;
    Session hsession = null;
    javax.mail.Session msession = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();
        msession = (javax.mail.Session) ctx.lookup(smtpSessionFactory);

        Users user = getUser(hsession, username);

        Criteria crit = hsession.createCriteria(Identity.class);
        crit.add(Restrictions.eq("users", getUser(hsession, username)));
        crit.add(Restrictions.eq("ideActive", new Boolean(true)));
        crit.add(Restrictions.eq("ideDefault", new Boolean(true)));

        Identity identity = (Identity) crit.uniqueResult();

        if (identity != null) {
            InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
            InternetAddress _to = InternetAddress.parse(to)[0];

            if (_from.getAddress().equals(_to.getAddress())) {
                return;
            }

            HtmlEmail email = new HtmlEmail();
            email.setMailSession(msession);

            email.setFrom(_from.getAddress(), _from.getPersonal());
            email.addTo(_to.getAddress(), _to.getPersonal());

            Iterator it = user.getMailPreferenceses().iterator();
            MailPreferences mailPreferences = (MailPreferences) it.next();

            email.setSubject(mailPreferences.getMaprVacationSubject());
            email.setHtmlMsg("<p>" + mailPreferences.getMaprVacationBody() + "</p><p>"
                    + mailPreferences.getMaprSignature() + "</p>");

            email.setCharset(Charset.defaultCharset().displayName());

            email.send();
        }
    } catch (Exception e) {
    } finally {
    }
}

From source file:com.zxy.commons.email.MailMessageUtils.java

/**
 * smtp??/*  www  .j  a  v a  2 s  . c o m*/
 * 
 * @param subject subject
 * @param htmlBody htmlBody
 * @param properties properties
 * @param from from
 * @param toList toList
 * @param ccList ccList
 * @param bccList bccList
 * @param embedUrls 
 * @throws EmailException EmailException
 */
@SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops", "PMD.UseStringBufferForStringAppends" })
public static void sendMail(String subject, String htmlBody, Map<String, String> properties, String from,
        List<String> toList, List<String> ccList, List<String> bccList, Map<String, URL> embedUrls)
        throws EmailException {
    HtmlEmail htmlEmail = getEmail();
    // from?
    if (!Strings.isNullOrEmpty(from)) {
        Address fromMailbox = parseMailbox(from);
        if (fromMailbox != null && StringUtils.isNotBlank(from)) {
            htmlEmail.setFrom(fromMailbox.getAddress(), fromMailbox.getName());
        }
    }
    // to?
    if (toList != null && !toList.isEmpty()) {
        for (String to : toList) {
            if (StringUtils.isNotBlank(to)) {
                Address toMailbox = parseMailbox(to);
                htmlEmail.addTo(toMailbox.getAddress(), toMailbox.getName());
            }
        }
    }
    // cc?
    if (ccList != null && !ccList.isEmpty()) {
        for (String cc : ccList) {
            if (StringUtils.isNotBlank(cc)) {
                Address ccMailbox = parseMailbox(cc);
                htmlEmail.addCc(ccMailbox.getAddress(), ccMailbox.getName());
            }
        }
    }
    // bcc?
    if (bccList != null && !bccList.isEmpty()) {
        for (String bcc : bccList) {
            if (StringUtils.isNotBlank(bcc)) {
                Address bccMailbox = parseMailbox(bcc);
                htmlEmail.addBcc(bccMailbox.getAddress(), bccMailbox.getName());
            }
        }
    }
    // 
    htmlEmail.setSubject(subject);
    htmlEmail.setHtmlMsg(htmlBody);
    htmlEmail.setSentDate(new Date());
    // 
    if (properties != null) {
        htmlEmail.setHeaders(properties);
    }
    // 
    if (embedUrls != null && !embedUrls.isEmpty()) {
        for (Map.Entry<String, URL> entry : embedUrls.entrySet()) {
            String cid = entry.getKey();
            URL url = entry.getValue();
            String fileName = StringUtils.substringAfterLast(url.getPath(), "/");
            if (StringUtils.isBlank(fileName)) {
                fileName = cid;
            } else {
                fileName += IdUtils.genStringId();
            }
            htmlEmail.embed(new URLDataSource(url), fileName, cid);
        }
    }
    htmlEmail.send();
}

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  ww. j  av  a2  s  .  c o  m
        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:com.ipc.service.SignUpService.java

public String sendhtmlmail(int uid, String key, String email) throws IOException, EmailException {
    HtmlEmail sendemail = new HtmlEmail();
    sendemail.setCharset("euc-kr");
    sendemail.setHostName("smtp.worksmobile.com");
    sendemail.addTo(email);// w ww.j  a v a2  s .co m
    sendemail.setFrom("jinuk@ideaconcert.com", "");
    sendemail.setSubject("?  ?? ?.");
    sendemail.setAuthentication("jinuk@ideaconcert.com", "tpxmapsb1");
    sendemail.setSmtpPort(465);
    sendemail.setSSL(true); //?
    sendemail.setTLS(true);
    sendemail.setDebug(true);
    String htmlmsg = "<html><div style='width:1000px; float:left; border-bottom:2px solid #45d4fe; padding-bottom:5px;box-sizing:border-box;'></div><div style='width:1000px;float:left; box-sizing:border-box; padding:15px;'><h2>? ?  ? .</h2><div style='width:100%; float:left; box-sizing:border-box; border:5px solid #f9f9f9; text-align:center; padding:40px 0 40px 0;'><span>   ? .</span><br><a href='http://localhost:8088/signup/permit?uid="
            + uid + "&key=" + key
            + "'><button style='width:150px; height:40px; background:none; border:2px solid #45d4fe; font-size:1.1rem; text-decoration: none;font-weight:bold; margin-top:10px;'></button></a></div></div></html>";
    System.out.println(htmlmsg);
    sendemail.setHtmlMsg(htmlmsg);
    try {
        sendemail.send();
    } catch (Exception e) {
        System.out.println("NOTOK");
        return "NOTOK";
    }
    return "OK";
}

From source file:Email.CommonsEmail.java

/**
 * Envia email no formato HTML/*from w ww . j a  v  a 2 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();
    }
}