Example usage for org.springframework.mail.javamail MimeMessageHelper setCc

List of usage examples for org.springframework.mail.javamail MimeMessageHelper setCc

Introduction

In this page you can find the example usage for org.springframework.mail.javamail MimeMessageHelper setCc.

Prototype

public void setCc(String[] cc) throws MessagingException 

Source Link

Usage

From source file:org.opentides.eventhandler.EmailHandler.java

public void sendEmail(String[] to, String[] cc, String[] bcc, String replyTo, String subject, String body,
        File[] attachments) {/*from  ww  w  . j a  v  a 2  s .c  o m*/
    try {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

        mimeMessageHelper.setTo(toInetAddress(to));
        InternetAddress[] ccAddresses = toInetAddress(cc);
        if (ccAddresses != null)
            mimeMessageHelper.setCc(ccAddresses);
        InternetAddress[] bccAddresses = toInetAddress(bcc);
        if (bccAddresses != null)
            mimeMessageHelper.setBcc(bccAddresses);
        if (!StringUtil.isEmpty(replyTo))
            mimeMessageHelper.setReplyTo(replyTo);
        Map<String, Object> templateVariables = new HashMap<String, Object>();

        templateVariables.put("message-title", subject);
        templateVariables.put("message-body", body);

        StringWriter writer = new StringWriter();
        VelocityEngineUtils.mergeTemplate(velocityEngine, mailVmTemplate, "UTF-8", templateVariables, writer);

        mimeMessageHelper.setFrom(new InternetAddress(this.fromEmail, this.fromName));
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(writer.toString(), true);

        // check for attachment
        if (attachments != null && attachments.length > 0) {
            for (File attachment : attachments) {
                mimeMessageHelper.addAttachment(attachment.getName(), attachment);
            }
        }

        /**
         * The name of the identifier should be image
         * the number after the image name is the counter 
         * e.g. <img src="cid:image1" />
         */
        if (imagesPath != null && imagesPath.size() > 0) {
            int x = 1;
            for (String path : imagesPath) {
                FileSystemResource res = new FileSystemResource(new File(path));
                String imageName = "image" + x;
                mimeMessageHelper.addInline(imageName, res);
                x++;
            }
        }
        javaMailSender.send(mimeMessage);
    } catch (MessagingException e) {
        _log.error(e, e);
    } catch (UnsupportedEncodingException uee) {
        _log.error(uee, uee);
    }
}

From source file:csns.util.EmailUtils.java

public boolean sendHtmlMail(Email email) {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message);

    try {//from   ww  w  .  j av a2 s.  c o m
        message.setContent(getHtml(email), "text/html");

        helper.setSubject(email.getSubject());
        helper.setFrom(email.getAuthor().getPrimaryEmail());
        helper.setCc(email.getAuthor().getPrimaryEmail());
        String addresses[] = getAddresses(email.getRecipients(), email.isUseSecondaryEmail())
                .toArray(new String[0]);
        if (addresses.length > 1) {
            helper.setTo(appEmail);
            helper.setBcc(addresses);
        } else
            helper.setTo(addresses);

        mailSender.send(message);

        logger.info(email.getAuthor().getUsername() + " sent email to "
                + StringUtils.arrayToCommaDelimitedString(addresses));

        return true;
    } catch (MessagingException e) {
        logger.warn("Fail to send MIME message", e);
    }

    return false;
}

From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java

public void handleResult(final MultiFilesResult result) throws MessagingException, IOException {
    final Serializable responseBody = result.getMeta().get(EMAIL_BODY_META_NAME);
    final String responseText = responseBody instanceof File ? FileUtils.readFileToString((File) responseBody)
            : responseBody.toString();/*from w  ww  . jav a  2 s . c o  m*/

    final MimeMessage mimeMessage = mailSender.createMimeMessage();
    final MimeMessageHelper mmh = new MimeMessageHelper(mimeMessage, true);

    mmh.setFrom((String) result.getMeta().get(EMAIL_ADDRESSEE_META_NAME));
    mmh.setTo((String) result.getMeta().get(EMAIL_REPLY_TO_META_NAME));
    mmh.setCc((String[]) result.getMeta().get(EMAIL_REPLY_CC_META_NAME));
    mmh.setSubject("RE: " + result.getMeta().get(EMAIL_SUBJECT_META_NAME));

    if (result.isSuccess()) {
        mmh.setText(responseText);
        for (final File resultFile : result.getPayload()) {
            mmh.addAttachment(resultFile.getName(), resultFile);
        }
    } else {
        mmh.setText(FileUtils.readFileToString(result.getPayload()[0]));
    }

    final Message<MimeMailMessage> message = new GenericMessage<MimeMailMessage>(new MimeMailMessage(mmh));
    outboundEmailChannel.send(message);
}

From source file:com.devnexus.ting.core.service.impl.CfpToMailTransformer.java

public MimeMessage prepareMailToSpeaker(CfpSubmission cfpSubmission) {

    String templateHtml = SystemInformationUtils.getCfpHtmlEmailTemplate();
    String templateText = SystemInformationUtils.getCfpTextEmailTemplate();

    String renderedHtmlTemplate = applyMustacheTemplate(cfpSubmission, templateHtml);
    String renderedTextTemplate = applyMustacheTemplate(cfpSubmission, templateText);

    MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    MimeMessageHelper messageHelper;
    try {/*from  w w w .j  a  va2s  . co  m*/
        messageHelper = new MimeMessageHelper(mimeMessage, true);
        messageHelper.setText(renderedTextTemplate, renderedHtmlTemplate);

        messageHelper.setFrom(fromUser);

        for (CfpSubmissionSpeaker submissionSpeaker : cfpSubmission.getSpeakers()) {
            messageHelper.addTo(submissionSpeaker.getEmail());
        }

        if (StringUtils.hasText(this.ccUser)) {
            messageHelper.setCc(this.ccUser);
        }

        messageHelper.setSubject("DevNexus 2015 - CFP - " + cfpSubmission.getSpeakersAsString(false));

    } catch (MessagingException e) {
        throw new IllegalStateException("Error creating mail message for CFP: " + cfpSubmission, e);
    }

    return messageHelper.getMimeMessage();
}

From source file:org.jnap.core.email.Email.java

public void prepare(MimeMessage mimeMessage) throws Exception {
    final EmailAccountInfo acc = getAccountInfo();
    boolean multipart = StringUtils.isNotBlank(getHtmlText())
            || (getInlineResources() != null && getInlineResources().size() > 0)
            || (getAttachments() != null && getAttachments().size() > 0);

    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, multipart);
    if (acc.getFromName() != null) {
        helper.setFrom(acc.getFromEmailAddress(), acc.getFromName());
    } else {//from   w ww.j  a  va2 s.  c o  m
        this.setFrom(acc.getFromEmailAddress());
    }
    helper.setTo(getTo());
    if (getCc() != null) {
        helper.setCc(getCc());
    }
    if (getBcc() != null) {
        helper.setBcc(getBcc());
    }
    helper.setSentDate(new Date());
    mimeMessage.setSubject(getMessage(getSubject()), this.encoding);

    // sender info
    if (acc != null && StringUtils.isNotBlank(acc.getFromName())) {
        helper.setFrom(acc.getFromEmailAddress(), getMessage(acc.getFromName()));
    } else {
        helper.setFrom(acc.getFromEmailAddress());
    }
    if (acc != null && StringUtils.isNotBlank(acc.getReplyToEmailAddress())) {
        if (StringUtils.isNotBlank(acc.getReplyToName())) {
            helper.setReplyTo(acc.getReplyToEmailAddress(), acc.getReplyToName());
        } else {
            helper.setReplyTo(acc.getReplyToEmailAddress());
        }
    }

    final boolean hasHtmlText = StringUtils.isNotBlank(getHtmlText());
    final boolean hasText = StringUtils.isNotBlank(getText());
    if (hasHtmlText && hasText) {
        helper.setText(getText(), getHtmlText());
    } else if (hasHtmlText || hasText) {
        helper.setText(hasHtmlText ? getHtmlText() : getText());
    }

    // set headers
    final Map<String, String> mailHeaders = this.getHeaders();
    for (String header : mailHeaders.keySet()) {
        mimeMessage.addHeader(header, mailHeaders.get(header));
    }

    // add inline resources
    final Map<String, Resource> inlineRes = this.getInlineResources();
    if (inlineRes != null) {
        for (String cid : inlineRes.keySet()) {
            helper.addInline(cid, inlineRes.get(cid));
        }
    }
    // add attachments
    final Map<String, Resource> attachments = this.getAttachments();
    if (attachments != null) {
        for (String attachmentName : attachments.keySet()) {
            helper.addAttachment(attachmentName, attachments.get(attachmentName));
        }
    }
}

From source file:com.springstudy.utils.email.MimeMailService.java

/**
 * ??MIME?.//ww w  . j ava 2  s  .  c om
 */
public boolean sendNotificationMail(com.gmk.framework.common.utils.email.Email email) {
    try {
        MimeMessage msg = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg, true, DEFAULT_ENCODING);
        //??????
        String from = Global.getConfig("productName");
        if (StringUtils.isNotEmpty(email.getFrom())) {
            from = from + "-" + email.getFrom();
        }
        helper.setFrom(Global.getConfig("mailFrom"), from);
        helper.setTo(email.getAddress());
        if (StringUtils.isNotEmpty(email.getCc())) {
            String cc[] = email.getCc().split(";");
            helper.setCc(cc);//?
        }
        //
        helper.setSubject(email.getSubject());
        //
        if (StringUtils.isNotEmpty(email.getTemplate())) {
            String content = generateContent(email.getTemplate(), email.getContentMap());
            helper.setText(content, true);
        } else {
            helper.setText(email.getContent());
        }
        //
        if (ListUtils.isNotEmpty(email.getAttachment())) {
            for (File file : email.getAttachment()) {
                helper.addAttachment(MimeUtility.encodeWord(file.getName()), file);
            }
        }
        mailSender.send(msg);
        logger.info("HTML??");
        return true;
    } catch (MessagingException e) {
        logger.error(email.getAddressee() + "-" + email.getSubject() + "-" + "", e);
    } catch (Exception e) {
        logger.error(email.getAddressee() + "-" + email.getSubject() + "-" + "??", e);
    }
    return false;
}

From source file:hornet.framework.mail.MailServiceImpl.java

/**
 * Adds the extra smtp field.//from  w  ww . ja va2 s  . c o  m
 *
 * @param paramMap
 *            the param map
 * @param helper
 *            the helper
 * @throws MessagingException
 *             the messaging exception
 */
protected void addExtraSmtpField(final Map<String, Object> paramMap, final MimeMessageHelper helper)
        throws MessagingException {

    if (paramMap != null) {
        if (paramMap.containsKey(SMTP_HEADER_REPLYTO)) {
            helper.setReplyTo((String) paramMap.get(SMTP_HEADER_REPLYTO));
        }
        if (paramMap.containsKey(SMTP_HEADER_BCC)) {
            helper.setBcc((String) paramMap.get(SMTP_HEADER_BCC));
        }
        if (paramMap.containsKey(SMTP_HEADER_CC)) {
            helper.setCc((String) paramMap.get(SMTP_HEADER_CC));
        }
        if (paramMap.containsKey(SMTP_HEADER_PRIORITY)) {
            helper.setPriority((Integer) paramMap.get(SMTP_HEADER_PRIORITY));
        }
        if (paramMap.containsKey(SMTP_HEADER_RETURNPATH)) {
            ((SMTPMessage) helper.getMimeMessage())
                    .setEnvelopeFrom((String) paramMap.get(SMTP_HEADER_RETURNPATH));
        }
        if (paramMap.containsKey(SMTP_ATTACHMENT_CONTENU)) {
            helper.addAttachment((String) paramMap.get(SMTP_ATTACHMENT_NOM),
                    (InputStreamSource) paramMap.get(SMTP_ATTACHMENT_CONTENU));
        }
    }
}

From source file:net.triptech.metahive.service.EmailSenderService.java

/**
 * Send an email message using the configured Spring sender. On success
 * record the sent message in the datastore for reporting purposes
 *
 * @param email the email//from w w w. j  ava  2  s  .c o  m
 * @param attachments the attachments
 * @throws ServiceException the service exception
 */
public final void send(final SimpleMailMessage email, TreeMap<String, Object> attachments)
        throws ServiceException {

    // Check to see whether the required fields are set (to, from, message)
    if (email.getTo() == null) {
        throw new ServiceException("Error sending email: Recipient " + "address required");
    }
    if (StringUtils.isBlank(email.getFrom())) {
        throw new ServiceException("Error sending email: Email requires " + "a from address");
    }
    if (StringUtils.isBlank(email.getText())) {
        throw new ServiceException("Error sending email: No email " + "message specified");
    }
    if (mailSender == null) {
        throw new ServiceException("The JavaMail sender has not " + "been configured");
    }

    // Prepare the email message
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = null;
    boolean htmlMessage = false;
    if (StringUtils.containsIgnoreCase(email.getText(), "<html")) {
        htmlMessage = true;
        try {
            helper = new MimeMessageHelper(message, true, "UTF-8");
        } catch (MessagingException me) {
            throw new ServiceException("Error preparing email for sending: " + me.getMessage());
        }
    } else {
        helper = new MimeMessageHelper(message);
    }

    try {
        helper.setTo(email.getTo());
        helper.setFrom(email.getFrom());
        helper.setSubject(email.getSubject());

        if (email.getCc() != null) {
            helper.setCc(email.getCc());
        }
        if (email.getBcc() != null) {
            helper.setBcc(email.getBcc());
        }

        if (htmlMessage) {
            String plainText = email.getText();
            try {
                ConvertHtmlToText htmlToText = new ConvertHtmlToText();
                plainText = htmlToText.convert(email.getText());
            } catch (Exception e) {
                logger.error("Error converting HTML to plain text: " + e.getMessage());
            }
            helper.setText(plainText, email.getText());
        } else {
            helper.setText(email.getText());
        }

        if (email.getSentDate() != null) {
            helper.setSentDate(email.getSentDate());
        } else {
            helper.setSentDate(Calendar.getInstance().getTime());
        }

    } catch (MessagingException me) {
        throw new ServiceException("Error preparing email for sending: " + me.getMessage());
    }

    // Append any attachments (if an HTML email)
    if (htmlMessage && attachments != null) {
        for (String id : attachments.keySet()) {
            Object reference = attachments.get(id);

            if (reference instanceof File) {
                try {
                    FileSystemResource res = new FileSystemResource((File) reference);
                    helper.addInline(id, res);
                } catch (MessagingException me) {
                    logger.error("Error appending File attachment: " + me.getMessage());
                }
            }
            if (reference instanceof URL) {
                try {
                    UrlResource res = new UrlResource((URL) reference);
                    helper.addInline(id, res);
                } catch (MessagingException me) {
                    logger.error("Error appending URL attachment: " + me.getMessage());
                }
            }
        }
    }

    // Send the email message
    try {
        mailSender.send(message);
    } catch (MailException me) {
        logger.error("Error sending email: " + me.getMessage());
        throw new ServiceException("Error sending email: " + me.getMessage());
    }
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java

protected void addMailRecipients(ReportJobMailNotification mailNotification, MimeMessageHelper messageHelper)
        throws MessagingException {
    List toAddresses = mailNotification.getToAddresses();
    if (toAddresses != null && !toAddresses.isEmpty()) {
        String[] addressArray = new String[toAddresses.size()];
        toAddresses.toArray(addressArray);
        messageHelper.setTo(addressArray);
    }//from  w w w.  j  av a 2 s. c o m

    List ccAddresses = mailNotification.getCcAddresses();
    if (ccAddresses != null && !ccAddresses.isEmpty()) {
        String[] addressArray = new String[ccAddresses.size()];
        ccAddresses.toArray(addressArray);
        messageHelper.setCc(addressArray);
    }
    List bccAddresses = mailNotification.getBccAddresses();
    if (bccAddresses != null && !bccAddresses.isEmpty()) {
        String[] addressArray = new String[bccAddresses.size()];
        bccAddresses.toArray(addressArray);
        messageHelper.setBcc(addressArray);
    }
}