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

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

Introduction

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

Prototype

HtmlEmail

Source Link

Usage

From source file:com.qwazr.connectors.EmailConnector.java

@JsonIgnore
public HtmlEmail getNewHtmlEmail(Map<String, Object> params) throws EmailException {
    HtmlEmail email = new HtmlEmail();
    generic_params(email, params);//  w ww. ja v  a 2  s  .  c  o m
    return email;
}

From source file:de.cosmocode.palava.services.mail.EmailFactory.java

@SuppressWarnings("unchecked")
Email build(Document document, Embedder embed) throws EmailException, FileNotFoundException {
    /* CHECKSTYLE:ON */

    final Element root = document.getRootElement();

    final List<Element> messages = root.getChildren("message");
    if (messages.isEmpty())
        throw new IllegalArgumentException("No messages found");

    final List<Element> attachments = root.getChildren("attachment");

    final Map<ContentType, String> available = new HashMap<ContentType, String>();

    for (Element element : messages) {
        final String type = element.getAttributeValue("type");
        final ContentType messageType = StringUtils.equals(type, "html") ? ContentType.HTML : ContentType.PLAIN;
        if (available.containsKey(messageType)) {
            throw new IllegalArgumentException("Two messages with the same types have been defined.");
        }//from w ww. java2  s .  c  o  m
        available.put(messageType, element.getText());
    }

    final Email email;

    if (available.containsKey(ContentType.HTML) || attachments.size() > 0) {
        final HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setCharset(CHARSET);

        if (embed.hasEmbeddings()) {
            htmlEmail.setSubType("related");
        } else if (attachments.size() > 0) {
            htmlEmail.setSubType("related");
        } else {
            htmlEmail.setSubType("alternative");
        }

        /**
         * Add html message
         */
        if (available.containsKey(ContentType.HTML)) {
            htmlEmail.setHtmlMsg(available.get(ContentType.HTML));
        }

        /**
         * Add plain text alternative
         */
        if (available.containsKey(ContentType.PLAIN)) {
            htmlEmail.setTextMsg(available.get(ContentType.PLAIN));
        }

        /**
         * Embedded binary data
         */
        for (Map.Entry<String, String> entry : embed.getEmbeddings().entrySet()) {
            final String path = entry.getKey();
            final String cid = entry.getValue();
            final String name = embed.name(path);

            final File file;

            if (path.startsWith(File.separator)) {
                file = new File(path);
            } else {
                file = new File(embed.getResourcePath(), path);
            }

            if (file.exists()) {
                htmlEmail.embed(new FileDataSource(file), name, cid);
            } else {
                throw new FileNotFoundException(file.getAbsolutePath());
            }
        }

        /**
         * Attached binary data
         */
        for (Element attachment : attachments) {
            final String name = attachment.getAttributeValue("name", "");
            final String description = attachment.getAttributeValue("description", "");
            final String path = attachment.getAttributeValue("path");

            if (path == null)
                throw new IllegalArgumentException("Attachment path was not set");
            File file = new File(path);

            if (!file.exists())
                file = new File(embed.getResourcePath(), path);

            if (file.exists()) {
                htmlEmail.attach(new FileDataSource(file), name, description);
            } else {
                throw new FileNotFoundException(file.getAbsolutePath());
            }
        }

        email = htmlEmail;
    } else if (available.containsKey(ContentType.PLAIN)) {
        email = new SimpleEmail();
        email.setCharset(CHARSET);
        email.setMsg(available.get(ContentType.PLAIN));
    } else {
        throw new IllegalArgumentException("No valid message found in template.");
    }

    final String subject = root.getChildText("subject");
    email.setSubject(subject);

    final Element from = root.getChild("from");
    final String fromAddress = from == null ? null : from.getText();
    final String fromName = from == null ? fromAddress : from.getAttributeValue("name", fromAddress);
    email.setFrom(fromAddress, fromName);

    final Element to = root.getChild("to");
    if (to != null) {
        final String toAddress = to.getText();
        if (StringUtils.isNotBlank(toAddress) && toAddress.contains(EMAIL_SEPARATOR)) {
            final String[] toAddresses = toAddress.split(EMAIL_SEPARATOR);
            for (String address : toAddresses) {
                email.addTo(address);
            }
        } else if (StringUtils.isNotBlank(toAddress)) {
            final String toName = to.getAttributeValue("name", toAddress);
            email.addTo(toAddress, toName);
        }
    }

    final Element cc = root.getChild("cc");
    if (cc != null) {
        final String ccAddress = cc.getText();
        if (StringUtils.isNotBlank(ccAddress) && ccAddress.contains(EMAIL_SEPARATOR)) {
            final String[] ccAddresses = ccAddress.split(EMAIL_SEPARATOR);
            for (String address : ccAddresses) {
                email.addCc(address);
            }
        } else if (StringUtils.isNotBlank(ccAddress)) {
            final String ccName = cc.getAttributeValue("name", ccAddress);
            email.addCc(ccAddress, ccName);
        }
    }

    final Element bcc = root.getChild("bcc");
    if (bcc != null) {
        final String bccAddress = bcc.getText();
        if (StringUtils.isNotBlank(bccAddress) && bccAddress.contains(EMAIL_SEPARATOR)) {
            final String[] bccAddresses = bccAddress.split(EMAIL_SEPARATOR);
            for (String address : bccAddresses) {
                email.addBcc(address);
            }
        } else if (StringUtils.isNotBlank(bccAddress)) {
            final String bccName = bcc.getAttributeValue("name", bccAddress);
            email.addBcc(bccAddress, bccName);
        }
    }

    final Element replyTo = root.getChild("replyTo");
    if (replyTo != null) {
        final String replyToAddress = replyTo.getText();
        if (StringUtils.isNotBlank(replyToAddress) && replyToAddress.contains(EMAIL_SEPARATOR)) {
            final String[] replyToAddresses = replyToAddress.split(EMAIL_SEPARATOR);
            for (String address : replyToAddresses) {
                email.addReplyTo(address);
            }
        } else if (StringUtils.isNotBlank(replyToAddress)) {
            final String replyToName = replyTo.getAttributeValue("name", replyToAddress);
            email.addReplyTo(replyToAddress, replyToName);
        }
    }

    return email;
}

From source file:com.actionbazaar.email.EmailService.java

/**
 * Sends out an email/*from  w  ww.  j  a v a  2 s  . co m*/
 * @param message - message to be sent
 */
public void onMessage(Message message) {

    try {
        EmailRequest emailRequest = (EmailRequest) ((ObjectMessage) message).getObject();

        Query query = entityManager.createQuery("select e from Email e where e.action = ?1");
        query.setParameter(1, emailRequest.getAction());
        List results = query.getResultList();
        if (results.size() != 1) {
            logger.severe("A total of " + results.size() + " email templates were returned for action "
                    + emailRequest.getAction());
            return;
        }
        System.out.println("--> Sending email.");
        Email emailInfo = (Email) results.get(0);
        logger.info("Speaker Directory: " + attachmentDirectory);
        HtmlEmail email = new HtmlEmail();
        email.setMailSession(mailSession);
        email.setTextMsg("Hello World!");
        //  email.setSubject(template.getSubject());
        email.addTo("rcuprak@mac.com");
        email.setFrom("java@ctjava.org");
        //  email.send();

        /*       emailTemplate.process(emailRecipient.getReplacementTokens());
                for (Map.Entry<String,File> entry : emailTemplate.getCidMappings().entrySet()) {
                    email.embed(entry.getValue(),entry.getKey());
                }
                email.setHtmlMsg(emailTemplate.getPatchedEmail());
          */
    } catch (Throwable t) {
        t.printStackTrace();
        //context.setRollbackOnly();
    }
}

From source file:io.marto.aem.utils.email.FreemarkerTemplatedMailer.java

private HtmlEmail constructEmail(final String[] recipients, String sender, final String subject,
        String template, Object model) throws EmailException {
    final HtmlEmail email = new HtmlEmail();

    email.setMsg(renderBody(template, model));
    if (subject != null) {
        email.setSubject(subject);//from w  ww . j a  va  2s  .  c  o m
    }
    if (sender != null) {
        email.setFrom(sender);
    }

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

    return email;
}

From source file:com.qwazr.library.email.EmailConnector.java

@JsonIgnore
public HtmlEmail getNewHtmlEmail(final Map<String, Object> params) throws EmailException {
    HtmlEmail email = new HtmlEmail();
    generic_params(email, params);/*from   w w  w  .  j  a v  a  2  s.c o m*/
    return email;
}

From source file:enviocorreo.EnviadorCorreo.java

/**
 * Enva un correo electrnico. Utiliza la biblioteca Apache Commons Email,
 * accesible va <a href="https://commons.apache.org/proper/commons-email/">https://commons.apache.org/proper/commons-email/</a>
 *
 * @param destinatario//ww  w.j  av a 2 s .  c o  m
 * @param asunto
 * @param mensaje
 * @return
 */
public boolean enviarCorreoE(String destinatario, String asunto, String mensaje) {
    boolean resultado = false;

    HtmlEmail email = new HtmlEmail();
    email.setHostName(host);
    email.setSmtpPort(puerto);
    email.setAuthenticator(new DefaultAuthenticator(usuario, password));

    if (isGmail) {
        email.setSSLOnConnect(true);
    } else {
        email.setStartTLSEnabled(true);
    }

    try {
        email.setFrom(usuario + "<dominio del correo>");
        email.setSubject(asunto);
        email.setHtmlMsg(mensaje);
        email.addTo(destinatario);
        email.send();
        resultado = true;
    } catch (EmailException eme) {
        mensaje = "Ocurri un error al hacer el envo de correo.";
        mensajeError = eme.toString();
    }

    return resultado;
}

From source file:cl.alma.scrw.bpmn.tasks.MailActivityBehavior.java

protected HtmlEmail createHtmlEmail(String text, String html) {
    HtmlEmail email = new HtmlEmail();
    try {//w  w w .ja v  a2s  .c  o  m
        email.setHtmlMsg(html);
        if (text != null) { // for email clients that don't support html
            email.setTextMsg(text);
        }
        return email;
    } catch (EmailException e) {
        throw new ActivitiException("Could not create HTML email", e);
    }
}

From source file:com.aquest.emailmarketing.web.service.SendEmail.java

/**
 * Send email.//  w w w.jav a 2 s . co m
 *
 * @param broadcast the broadcast
 * @param emailConfig the email config
 * @param emailList the email list
 * @throws EmailException the email exception
 * @throws MalformedURLException the malformed url exception
 * @throws InterruptedException the interrupted exception
 */
@Async
public void sendEmail(Broadcast broadcast, EmailConfig emailConfig, EmailList emailList)
        throws EmailException, MalformedURLException, InterruptedException {

    Timestamp curTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());
    // email configuration part
    HtmlEmail email = new HtmlEmail();
    email.setSmtpPort(emailConfig.getPort());
    email.setHostName(emailConfig.getHostname());
    email.setAuthenticator(new DefaultAuthenticator(emailConfig.getUsername(), emailConfig.getPassword()));
    email.setSSLOnConnect(emailConfig.isSslonconnect());
    email.setDebug(emailConfig.isDebug());
    email.setFrom(emailConfig.getFrom_address()); //ovde dodati i email from description

    System.out.println(emailList);
    HashMap<String, String> variables = processVariableService.ProcessVariable(emailList);

    for (String keys : variables.keySet()) {
        System.out.println("key:" + keys + ", value:" + variables.get(keys));
    }

    String processSubject = broadcast.getSubject();
    String newHtml = broadcast.getHtmlbody_embed();
    String newPlainText = broadcast.getPlaintext();

    for (String key : variables.keySet()) {
        processSubject = processSubject.replace("[" + key + "]", variables.get(key));
        System.out.println(key + "-" + variables.get(key));
        newHtml = newHtml.replace("[" + key + "]", variables.get(key));
        newPlainText = newPlainText.replace("[" + key + "]", variables.get(key));
    }
    System.out.println(processSubject);
    email.setSubject(processSubject);
    email.addTo(emailList.getEmail());

    String image = embeddedImageService.getEmbeddedImages(broadcast.getBroadcast_id()).getUrl();
    List<String> images = Arrays.asList(image.split(";"));
    for (int j = 0; j < images.size(); j++) {
        System.out.println(images.get(j));
    }
    for (int i = 0; i < images.size(); i++) {
        String id = email.embed(images.get(i), "Slika" + i);
        newHtml = newHtml.replace("[IMAGE:" + i + "]", "cid:" + id);
    }

    Config config = configService.getConfig("trackingurl");
    //DONE: Create jsp page for tracking server url
    String serverUrl = config.getValue();
    System.out.println(serverUrl);
    Base64 base64 = new Base64(true);

    Pattern pattern = Pattern.compile("<%tracking=(.*?)=tracking%>");
    Matcher matcher = pattern.matcher(newHtml);
    while (matcher.find()) {
        String url = matcher.group(1);
        System.out.println(url);
        logger.debug(url);
        String myEncryptedUrl = new String(base64.encode(url.getBytes()));

        String oldurl = "<%tracking=" + url + "=tracking%>";
        logger.debug(oldurl);
        System.out.println(oldurl);
        String newurl = serverUrl + "tracking?id=" + myEncryptedUrl;
        logger.debug(newurl);
        System.out.println(newurl);
        newHtml = newHtml.replace(oldurl, newurl);
    }
    //        System.out.println(newHtml);

    email.setHtmlMsg(newHtml);
    email.setTextMsg(newPlainText);
    try {
        System.out.println("A ovo ovde?");
        email.send();
        emailList.setStatus("SENT");
        emailList.setProcess_dttm(curTimestamp);
        emailListService.SaveOrUpdate(emailList);
    } catch (Exception e) {
        logger.error(e);
    }
    // time in seconds to wait between 2 mails
    TimeUnit.SECONDS.sleep(emailConfig.getWait());
}

From source file:com.perceptive.epm.perkolcentral.bl.ImageNowLicenseBL.java

@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.SERIALIZABLE, rollbackFor = ExceptionWrapper.class)
public void addImageNowLicenseRequest(Imagenowlicenses imagenowlicenses, String groupRequestedFor,
        String employeeUIDWhoRequestedLicense, File sysfpFile, String originalFileName)
        throws ExceptionWrapper {
    try {/*from  ww  w.j a v a  2s. c o m*/
        imageNowLicenseDataAccessor.addImageNowLicense(imagenowlicenses, groupRequestedFor,
                employeeUIDWhoRequestedLicense);
        if (!new File(fileUploadPath).exists())
            FileUtils.forceMkdir(new File(fileUploadPath));
        File filePathForThisRequest = new File(
                FilenameUtils.concat(fileUploadPath, imagenowlicenses.getImageNowLicenseRequestId()));
        FileUtils.forceMkdir(filePathForThisRequest);
        File fileNameToCopy = new File(
                FilenameUtils.concat(filePathForThisRequest.getAbsolutePath(), originalFileName));
        FileUtils.copyFile(sysfpFile, fileNameToCopy);
        //Send the email
        String messageToSend = String.format(Constants.email_license_request,
                imagenowlicenses.getEmployeeByRequestedByEmployeeId().getEmployeeName(),
                imagenowlicenses.getGroups().getGroupName(),
                new SimpleDateFormat("dd-MMM-yyyy").format(imagenowlicenses.getLicenseRequestedOn()),
                imagenowlicenses.getImageNowVersion(), imagenowlicenses.getHostname(),
                Long.toString(imagenowlicenses.getNumberOfLicenses()));
        email = new HtmlEmail();
        email.setHostName(emailHost);
        email.setHtmlMsg(messageToSend);
        email.setSubject("ImageNow License Request");
        //email.setFrom("ImageNowLicenseRequest@perceptivesoftware.com", "ImageNow License Request");
        email.setFrom("ImageNowLicenseRequest@lexmark.com", "ImageNow License Request");
        // Create the attachment
        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath(fileNameToCopy.getAbsolutePath());
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription(originalFileName);
        attachment.setName(originalFileName);
        email.attach(attachment);
        //Send mail to scrum masters
        for (EmployeeBO item : employeeBL.getAllEmployeesKeyedByGroupId().get(Integer.valueOf("14"))) {
            email.addTo(item.getEmail(), item.getEmployeeName());
        }
        //email.addTo("saibal.ghosh@perceptivesoftware.com","Saibal Ghosh");
        email.addCc(imagenowlicenses.getEmployeeByRequestedByEmployeeId().getEmail());
        email.send();

    } catch (Exception ex) {
        throw new ExceptionWrapper(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  a v  a2  s  . c  om
        }

        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();

}