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

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

Introduction

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

Prototype

public MultiPartEmail attach(final URL url, final String name, final String description) throws EmailException 

Source Link

Document

Attach a file located by its URL.

Usage

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

/**
 * //from   w  w w. java 2s .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:de.hybris.platform.acceleratorservices.email.impl.DefaultEmailService.java

@Override
public boolean send(final EmailMessageModel message) {
    if (message == null) {
        throw new IllegalArgumentException("message must not be null");
    }/*from ww  w  .  java 2s.co  m*/

    final boolean sendEnabled = getConfigurationService().getConfiguration()
            .getBoolean(EMAILSERVICE_SEND_ENABLED_CONFIG_KEY, true);
    if (sendEnabled) {
        try {
            final HtmlEmail email = getPerConfiguredEmail();
            email.setCharset("UTF-8");

            final List<EmailAddressModel> toAddresses = message.getToAddresses();
            if (CollectionUtils.isNotEmpty(toAddresses)) {
                email.setTo(getAddresses(toAddresses));
            } else {
                throw new IllegalArgumentException("message has no To addresses");
            }

            final List<EmailAddressModel> ccAddresses = message.getCcAddresses();
            if (ccAddresses != null && !ccAddresses.isEmpty()) {
                email.setCc(getAddresses(ccAddresses));
            }

            final List<EmailAddressModel> bccAddresses = message.getBccAddresses();
            if (bccAddresses != null && !bccAddresses.isEmpty()) {
                email.setBcc(getAddresses(bccAddresses));
            }

            final EmailAddressModel fromAddress = message.getFromAddress();
            email.setFrom(fromAddress.getEmailAddress(), nullifyEmpty(fromAddress.getDisplayName()));

            // Add the reply to if specified
            final String replyToAddress = message.getReplyToAddress();
            if (replyToAddress != null && !replyToAddress.isEmpty()) {
                email.setReplyTo(Collections.singletonList(createInternetAddress(replyToAddress, null)));
            }

            email.setSubject(message.getSubject());
            email.setHtmlMsg(getBody(message));

            // To support plain text parts use email.setTextMsg()

            final List<EmailAttachmentModel> attachments = message.getAttachments();
            if (attachments != null && !attachments.isEmpty()) {
                for (final EmailAttachmentModel attachment : attachments) {
                    try {
                        final DataSource dataSource = new ByteArrayDataSource(
                                getMediaService().getDataFromMedia(attachment), attachment.getMime());
                        email.attach(dataSource, attachment.getRealFileName(), attachment.getAltText());
                    } catch (final EmailException ex) {
                        LOG.error("Failed to load attachment data into data source [" + attachment + "]", ex);
                        return false;
                    }
                }
            }

            // Important to log all emails sent out
            LOG.info("Sending Email [" + message.getPk() + "] To [" + convertToStrings(toAddresses) + "] From ["
                    + fromAddress.getEmailAddress() + "] Subject [" + email.getSubject() + "]");

            // Send the email and capture the message ID
            final String messageID = email.send();

            message.setSent(true);
            message.setSentMessageID(messageID);
            message.setSentDate(new Date());
            getModelService().save(message);

            return true;
        } catch (final EmailException e) {
            LOG.warn("Could not send e-mail pk [" + message.getPk() + "] subject [" + message.getSubject()
                    + "] cause: " + e.getMessage());
            if (LOG.isDebugEnabled()) {
                LOG.debug(e);
            }
        }
    } else {
        LOG.warn("Could not send e-mail pk [" + message.getPk() + "] subject [" + message.getSubject() + "]");
        LOG.info("Email sending has been disabled. Check the config property 'emailservice.send.enabled'");
        return true;
    }

    return false;
}

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.");
        }//  ww  w .ja v  a 2s . co  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:nl.b3p.kaartenbalie.struts.Mailer.java

public ActionMessages send(ActionMessages errors)
        throws AddressException, MessagingException, IOException, Exception {

    HtmlEmail email = new HtmlEmail();

    String[] ds = null;/*  w  ww  .j ava 2s .c om*/
    if (mailTo != null && mailTo.trim().length() != 0) {
        ds = mailTo.split(",");
        for (int i = 0; i < ds.length; i++) {
            email.addTo(ds[i]);
        }
    }
    if (mailCc != null && mailCc.trim().length() != 0) {
        ds = mailCc.split(",");
        for (int i = 0; i < ds.length; i++) {
            email.addCc(ds[i]);
        }
    }
    if (mailBcc != null && mailBcc.trim().length() != 0) {
        ds = mailBcc.split(",");
        for (int i = 0; i < ds.length; i++) {
            email.addBcc(ds[i]);
        }
    }

    email.setFrom(mailFrom);
    email.setSubject(subject);
    email.setHostName(mailHost);

    if (isReturnReceipt()) {
        email.addHeader("Disposition-Notification-To", mailFrom);
    }

    if (attachmentName == null) {
        attachmentName = "attachment";
    }
    if (attachment != null) {
        URL attachUrl = null;
        try {
            attachUrl = new URL(attachment);
            email.attach(attachUrl, attachmentName, attachmentName);
        } catch (MalformedURLException mfue) {
        }
    }
    if (attachmentDataSource != null) {
        email.attach(attachmentDataSource, attachmentName, attachmentName);
    }

    email.setMsg(createHTML());

    // send the email
    email.send();

    return errors;
}

From source file:org.chenillekit.mail.services.impl.MailServiceImpl.java

/**
 * send a HTML message./*from w ww  .  j  av a  2  s .  c  o m*/
 *
 * @param headers    the mail headers
 * @param htmlBody   the mail body (HTML based)
 * @param dataSources array of data sources to attach at this mail
 *
 * @return true if mail successfull send
 */
public boolean sendHtmlMail(MailMessageHeaders headers, String htmlBody, DataSource... dataSources) {
    try {
        HtmlEmail email = new HtmlEmail();

        setEmailStandardData(email);

        setMailMessageHeaders(email, headers);

        if (dataSources != null) {
            for (DataSource dataSource : dataSources)
                email.attach(dataSource, dataSource.getName(), dataSource.getName());
        }

        email.setCharset(headers.getCharset());
        email.setHtmlMsg(htmlBody);

        String msgId = email.send();

        return true;
    } catch (EmailException e) {
        // FIXME Handle gracefully
        throw new RuntimeException(e);
    }
}

From source file:org.openhab.binding.mail.internal.MailBuilder.java

/**
 * Build the Mail// ww  w. j  ava  2s . co m
 *
 * @return instance of Email
 * @throws EmailException if something goes wrong
 */
public Email build() throws EmailException {
    Email mail;

    if (attachmentURLs.isEmpty() && attachmentFiles.isEmpty() && html.isEmpty()) {
        // text mail without attachments
        mail = new SimpleEmail();
        if (!text.isEmpty()) {
            mail.setMsg(text);
        }
    } else if (html.isEmpty()) {
        // text mail with attachments
        MultiPartEmail multipartMail = new MultiPartEmail();
        if (!text.isEmpty()) {
            multipartMail.setMsg(text);
        }
        for (File file : attachmentFiles) {
            multipartMail.attach(file);
        }
        for (URL url : attachmentURLs) {
            EmailAttachment attachment = new EmailAttachment();
            attachment.setURL(url);
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            multipartMail.attach(attachment);
        }
        mail = multipartMail;
    } else {
        // html email
        HtmlEmail htmlMail = new HtmlEmail();
        if (!text.isEmpty()) {
            // alternate text supplied
            htmlMail.setTextMsg(text);
            htmlMail.setHtmlMsg(html);
        } else {
            htmlMail.setMsg(html);
        }
        for (File file : attachmentFiles) {
            htmlMail.attach(new FileDataSource(file), "", "");
        }
        for (URL url : attachmentURLs) {
            EmailAttachment attachment = new EmailAttachment();
            attachment.setURL(url);
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            htmlMail.attach(attachment);
        }
        mail = htmlMail;
    }

    mail.setTo(recipients);
    mail.setSubject(subject);

    if (!sender.isEmpty()) {
        mail.setFrom(sender);
    }

    return mail;
}