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

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

Introduction

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

Prototype

public Email setBcc(final Collection<InternetAddress> aCollection) throws EmailException 

Source Link

Document

Set a list of "BCC" addresses.

Usage

From source file:com.dattack.jtoolbox.commons.email.HtmlEmailBuilder.java

/**
 * Builder method.//from   ww  w  . j a  v a2  s.  c  o  m
 *
 * @return the HtmlEmail
 * @throws EmailException
 *             if an error occurs while creating the email
 */
public HtmlEmail build() throws EmailException {

    if (hostname == null || hostname.isEmpty()) {
        throw new EmailException(String.format("Invalid SMTP server (hostname: '%s')", hostname));
    }

    if (from == null || from.isEmpty()) {
        throw new EmailException(String.format("Invalid email address (FROM: '%s'", from));
    }

    final HtmlEmail email = new HtmlEmail();
    email.setHostName(hostname);
    email.setFrom(from);
    email.setSubject(subject);

    if (message != null && !message.isEmpty()) {
        email.setMsg(message);
    }

    if (port > 0) {
        email.setSmtpPort(port);
    }

    if (username != null && !username.isEmpty()) {
        email.setAuthenticator(new DefaultAuthenticator(username, password));
    }

    if (sslOnConnect != null) {
        email.setSSLOnConnect(sslOnConnect);
    }

    if (startTlsEnabled != null) {
        email.setStartTLSEnabled(startTlsEnabled);
    }

    if (!toList.isEmpty()) {
        email.setTo(toList);
    }

    if (!ccList.isEmpty()) {
        email.setCc(ccList);
    }

    if (!bccList.isEmpty()) {
        email.setBcc(bccList);
    }
    return email;
}

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   w  w  w  .jav  a 2 s.c  o 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:org.infoglue.cms.util.mail.MailService.java

/**
 *
 * @param from the sender of the email.//from   w  w  w.ja va 2s.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);
    }
}