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

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

Introduction

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

Prototype

public void addCc(String cc) throws MessagingException 

Source Link

Usage

From source file:com.foilen.smalltools.email.EmailServiceSpring.java

@Override
public void sendEmail(EmailBuilder emailBuilder) {

    try {//from   www  .  j  a  v a  2s .  c om
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(emailBuilder.getFrom());
        for (String to : emailBuilder.getTos()) {
            helper.addTo(to);
        }
        for (String cc : emailBuilder.getCcs()) {
            helper.addCc(cc);
        }
        for (String bcc : emailBuilder.getBccs()) {
            helper.addBcc(bcc);
        }
        helper.setSubject(emailBuilder.getSubject());
        helper.setText(emailBuilder.getBody(), emailBuilder.isHtml());

        // Inline
        for (EmailAttachment emailAttachment : emailBuilder.getInlineAttachments()) {
            helper.addInline(emailAttachment.getId(), emailAttachment.getResource());
        }

        // Attachment
        for (EmailAttachment emailAttachment : emailBuilder.getAttachments()) {
            helper.addAttachment(emailAttachment.getId(), emailAttachment.getResource());
        }

        mailSender.send(message);
    } catch (Exception e) {
        throw new SmallToolsException("Could not send email", e);
    }
}

From source file:com.devnexus.ting.core.service.integration.GenericEmailToMimeMessageTransformer.java

@Transformer
public MimeMessage prepareMailToSpeaker(GenericEmail email) {

    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    MimeMessageHelper messageHelper;
    try {/*from  w  ww .j ava  2  s.c o m*/
        messageHelper = new MimeMessageHelper(mimeMessage, true);
        messageHelper.setText(email.getText(), email.getHtml());
        messageHelper.setFrom(email.getFrom());

        for (String emailToAddress : email.getTo()) {
            messageHelper.addTo(emailToAddress);
        }

        if (!email.getCc().isEmpty()) {
            for (String emailCcAddress : email.getCc()) {
                messageHelper.addCc(emailCcAddress);
            }
        }

        messageHelper.setSubject(email.getSubject());

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

    return messageHelper.getMimeMessage();
}

From source file:it.ozimov.springboot.templating.mail.utils.EmailToMimeMessage.java

@Override
public MimeMessage apply(final Email email) {
    final MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    final MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,
            fromNullable(email.getEncoding()).or(Charset.forName("UTF-8")).displayName());

    try {//w w  w .  j a va  2  s .  com
        messageHelper.setFrom(email.getFrom());
        if (ofNullable(email.getReplyTo()).isPresent()) {
            messageHelper.setReplyTo(email.getReplyTo());
        }
        if (ofNullable(email.getTo()).isPresent()) {
            for (final InternetAddress address : email.getTo()) {
                messageHelper.addTo(address);
            }
        }
        if (ofNullable(email.getCc()).isPresent()) {
            for (final InternetAddress address : email.getCc()) {
                messageHelper.addCc(address);
            }
        }
        if (ofNullable(email.getBcc()).isPresent()) {
            for (final InternetAddress address : email.getBcc()) {
                messageHelper.addBcc(address);
            }
        }
        if (ofNullable(email.getAttachments()).isPresent()) {
            for (final EmailAttachmentImpl attachment : email.getAttachments()) {
                try {
                    messageHelper.addAttachment(attachment.getAttachmentName(), attachment.getInputStream(),
                            attachment.getContentType().getType());
                } catch (IOException e) {
                    log.error("Error while converting Email to MimeMessage");
                    throw new EmailConversionException(e);
                }
            }
        }
        messageHelper.setSubject(ofNullable(email.getSubject()).orElse(""));
        messageHelper.setText(ofNullable(email.getBody()).orElse(""));

        if (nonNull(email.getSentAt())) {
            messageHelper.setSentDate(email.getSentAt());
        }
    } catch (MessagingException e) {
        log.error("Error while converting Email to MimeMessage");
        throw new EmailConversionException(e);
    }

    return mimeMessage;
}

From source file:com.sfs.dao.EmailMessageDAOImpl.java

/**
 * Send an email message using the configured Spring sender. On success
 * record the sent message in the datastore for reporting purposes
 *
 * @param emailMessage the email message
 *
 * @throws SFSDaoException the SFS dao exception
 *///from   w  ww .  j  a  va2  s  .c o  m
public final void send(final EmailMessageBean emailMessage) throws SFSDaoException {

    // Check to see whether the required fields are set (to, from, message)
    if (StringUtils.isBlank(emailMessage.getTo())) {
        throw new SFSDaoException("Error recording email: Recipient " + "address required");
    }
    if (StringUtils.isBlank(emailMessage.getFrom())) {
        throw new SFSDaoException("Error recording email: Email requires " + "a return address");
    }
    if (StringUtils.isBlank(emailMessage.getMessage())) {
        throw new SFSDaoException("Error recording email: No email " + "message specified");
    }
    if (javaMailSender == null) {
        throw new SFSDaoException("The EmailMessageDAO has not " + "been configured");
    }

    // Prepare the email message
    MimeMessage message = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = null;
    if (emailMessage.getHtmlMessage()) {
        try {
            helper = new MimeMessageHelper(message, true, "UTF-8");
        } catch (MessagingException me) {
            throw new SFSDaoException("Error preparing email for sending: " + me.getMessage());
        }
    } else {
        helper = new MimeMessageHelper(message);
    }
    if (helper == null) {
        throw new SFSDaoException("The MimeMessageHelper cannot be null");
    }
    try {
        if (StringUtils.isNotBlank(emailMessage.getTo())) {
            StringTokenizer tk = new StringTokenizer(emailMessage.getTo(), ",");
            while (tk.hasMoreTokens()) {
                String address = tk.nextToken();
                helper.addTo(address);
            }
        }
        if (StringUtils.isNotBlank(emailMessage.getCC())) {
            StringTokenizer tk = new StringTokenizer(emailMessage.getCC(), ",");
            while (tk.hasMoreTokens()) {
                String address = tk.nextToken();
                helper.addCc(address);
            }
        }
        if (StringUtils.isNotBlank(emailMessage.getBCC())) {
            StringTokenizer tk = new StringTokenizer(emailMessage.getBCC(), ",");
            while (tk.hasMoreTokens()) {
                String address = tk.nextToken();
                helper.addBcc(address);
            }
        }
        if (StringUtils.isNotBlank(emailMessage.getFrom())) {
            if (StringUtils.isNotBlank(emailMessage.getFromName())) {
                try {
                    helper.setFrom(emailMessage.getFrom(), emailMessage.getFromName());
                } catch (UnsupportedEncodingException uee) {
                    dataLogger.error("Error setting email from", uee);
                }
            } else {
                helper.setFrom(emailMessage.getFrom());
            }
        }
        helper.setSubject(emailMessage.getSubject());
        helper.setPriority(emailMessage.getPriority());
        if (emailMessage.getHtmlMessage()) {
            final String htmlText = emailMessage.getMessage();
            String plainText = htmlText;
            try {
                ConvertHtmlToText htmlToText = new ConvertHtmlToText();
                plainText = htmlToText.convert(htmlText);
            } catch (Exception e) {
                dataLogger.error("Error converting HTML to plain text: " + e.getMessage());
            }
            helper.setText(plainText, htmlText);
        } else {
            helper.setText(emailMessage.getMessage());
        }
        helper.setSentDate(emailMessage.getSentDate());

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

    // Append any attachments (if an HTML email)
    if (emailMessage.getHtmlMessage()) {
        for (String id : emailMessage.getAttachments().keySet()) {
            final Object reference = emailMessage.getAttachments().get(id);

            if (reference instanceof File) {
                try {
                    FileSystemResource res = new FileSystemResource((File) reference);
                    helper.addInline(id, res);
                } catch (MessagingException me) {
                    dataLogger.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) {
                    dataLogger.error("Error appending URL attachment: " + me.getMessage());
                }
            }
        }
    }

    // If not in debug mode send the email
    if (!debugMode) {
        deliver(emailMessage, message);
    }
}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

public void testEncodedFromToAddresses() throws Exception {
    // RFC1342// www.  j  a  v  a  2  s.c  o m
    String addressString = "ars.kov@gmail.com";
    String personalString = "?? ";
    InternetAddress address = new InternetAddress(addressString, personalString, "UTF-8");

    // Following method returns the address with quoted personal aka <["?? "] <ars.kov@gmail.com>>
    // NOTE! This should be coincided with RFC822MetadataExtracter. Would 'addresses' be quoted or not? 
    // String decodedAddress = address.toUnicodeString();
    // So, just using decode, for now
    String decodedAddress = MimeUtility.decodeText(address.toString());

    // InternetAddress.toString(new Address[] {address}) - is used in the RFC822MetadataExtracter
    // So, compare with that
    assertFalse("Non ASCII characters in the address should be encoded",
            decodedAddress.equals(InternetAddress.toString(new Address[] { address })));

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));

    MimeMessageHelper messageHelper = new MimeMessageHelper(message, false, "UTF-8");

    messageHelper.setText("This is a sample message for ALF-5647");
    messageHelper.setSubject("This is a sample message for ALF-5647");
    messageHelper.setFrom(address);
    messageHelper.addTo(address);
    messageHelper.addCc(address);

    // Creating the message node in the repository
    String name = AlfrescoImapConst.MESSAGE_PREFIX + GUID.generate();
    FileInfo messageFile = fileFolderService.create(testImapFolderNodeRef, name, ContentModel.TYPE_CONTENT);
    // Writing a content.
    new IncomingImapMessage(messageFile, serviceRegistry, message);

    // Getting the transformed properties from the repository
    // cm:originator, cm:addressee, cm:addressees, imap:messageFrom, imap:messageTo, imap:messageCc
    Map<QName, Serializable> properties = nodeService.getProperties(messageFile.getNodeRef());

    String cmOriginator = (String) properties.get(ContentModel.PROP_ORIGINATOR);
    String cmAddressee = (String) properties.get(ContentModel.PROP_ADDRESSEE);
    @SuppressWarnings("unchecked")
    List<String> cmAddressees = (List<String>) properties.get(ContentModel.PROP_ADDRESSEES);
    String imapMessageFrom = (String) properties.get(ImapModel.PROP_MESSAGE_FROM);
    String imapMessageTo = (String) properties.get(ImapModel.PROP_MESSAGE_TO);
    String imapMessageCc = (String) properties.get(ImapModel.PROP_MESSAGE_CC);

    assertNotNull(cmOriginator);
    assertEquals(decodedAddress, cmOriginator);
    assertNotNull(cmAddressee);
    assertEquals(decodedAddress, cmAddressee);
    assertNotNull(cmAddressees);
    assertEquals(1, cmAddressees.size());
    assertEquals(decodedAddress, cmAddressees.get(0));
    assertNotNull(imapMessageFrom);
    assertEquals(decodedAddress, imapMessageFrom);
    assertNotNull(imapMessageTo);
    assertEquals(decodedAddress, imapMessageTo);
    assertNotNull(imapMessageCc);
    assertEquals(decodedAddress, imapMessageCc);
}

From source file:org.emmanet.jobs.standAloneMailer.java

public void onSubmit() {
    /*  String[] euCountriesList = {"Austria", "Belgium", "Bulgaria", "Cyprus", "Czech Republic", "Denmark", "Estonia", "Finland", "France", "Germany", "Greece", "Hungary", "Ireland", "Italy", "Latvia", "Lithuania", "Luxembourg", "Malta", "Netherlands", "Poland", "Portugal", "Romania", "Slovakia", "Slovenia", "Spain", "Sweden", "United Kingdom"};
    String[] assocCountriesList = {"Albania", "Croatia", "Iceland", "Israel", "Liechtenstein", "Macedonia", "Montenegro", "Norway", "Serbia", "Switzerland", "Turkey"};
    Arrays.sort(euCountriesList);/* w w  w  .  j  av a  2  s  . c o m*/
    Arrays.sort(assocCountriesList);*/

    //read from file
    try {
        BufferedReader in = new BufferedReader(new FileReader(Configuration.get("MAILCONTENT")));
        String str;
        while ((str = in.readLine()) != null) {
            //content = content + str;
            content = (new StringBuilder()).append(content).append(str).toString();
        }

        in.close();
    } catch (IOException e) {
        e.printStackTrace();

    }
    subject = "EMMAservice TA / impact assessment";//New Cre driver mouse lines"
    System.out.println("Subject: " + subject + "\n\nContent: " + content);

    //iterate over database email results adding to bcc use map keys ae address to prevent dups
    setCc(new HashMap());
    //getCc().put(new String("emma@infrafrontier.eu"), "");
    //getCc().put(new String("emma@infrafrontier.eu"), "");
    // getCc().put(new String("sabine.fessele@helmholtz-muenchen.de"), "");
    getCc().put(new String("michael.hagn@helmholtz-muenchen.de"), "");
    getCc().put(new String("philw@ebi.ac.uk"), "");

    setBcc(new HashMap());
    //PeopleManager pm = new PeopleManager();
    WebRequests wr = new WebRequests();
    //List Bccs1 = wr.sciMails("sci_e_mail");
    //List Bccs2 = wr.sciMails("sci_e_mail");
    List Bccs = wr.sciMails("nullfield");//ListUtils.union(Bccs1,Bccs2);
    int BccSize = Bccs.size();
    System.out.println("Size of list is: " + BccSize);
    //user asked to be removed,don't want to remove from database as details for email needed
    //Bccs1.remove("kgroden@interchange.ubc.ca");
    //Bccs2.remove("kgroden@interchange.ubc.ca");
    for (it = Bccs.listIterator(); it.hasNext();) {
        // Object[] o = (Object[]) it.next();
        //System.out.println("object is:: " + o);
        String element = it.next().toString();

        //String country = o[1].toString();

        if (!Bcc.containsKey(it)) {

            // int index = Arrays.binarySearch(euCountriesList, country);

            // int index1 = Arrays.binarySearch(euCountriesList, country);

            //  if (index >= 0 || index1 >= 0) {
            // System.out.println("Country OK :- " + country);
            System.out.println("element is: " + element);
            Bcc.put(element, "");
            //  }
        }
    }

    MimeMessage message = getJavaMailSender().createMimeMessage();
    try {
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        //helper.setValidateAddresses(false);
        helper.setReplyTo("emma@infrafrontier.eu");
        helper.setFrom("emma@infrafrontier.eu");
        System.out.println("BCC SIZE -- " + Bcc.size());
        Iterator it1 = Bcc.keySet().iterator();

        while (it1.hasNext()) {
            String BccAddress = (String) it1.next();
            System.out.println("BccADDRESS===== " + BccAddress);
            if (BccAddress == null || BccAddress.trim().length() < 1
                    || !patternMatch(EMAIL_PATTERN, BccAddress)) {
                System.out
                        .println("The Scientists Email address field appears to have no value or is incorrect");
                BccSize = BccSize - 1;
            } else {
                //~~  
                helper.addBcc(BccAddress);
            }
        }
        System.out.println("CC SIZE -- " + Cc.size());
        Iterator i = Cc.keySet().iterator();
        while (i.hasNext()) {
            String CcAddress = (String) i.next();
            System.out.println("ccADDRESS===== " + CcAddress);
            helper.addCc(CcAddress);
        }

        helper.setTo("emma@infrafrontier.eu");//info@emmanet.org
        //helper.setCc("webmaster.emmanet.org");
        //helper.setBcc("philw@ebi.ac.uk");
        helper.setText(content, true);
        helper.setSubject(subject);
        String filePath = Configuration.get("TMPFILES");
        //String fileName = "PhenotypingSurveyCombinedNov2009.doc";
        //String fileName2 = "EMPReSSslimpipelines-1.pdf";
        //FileSystemResource file = new FileSystemResource(new File(filePath + fileName));
        // FileSystemResource file2 = new FileSystemResource(new File(filePath + fileName2));
        //helper.addAttachment(fileName, file);
        //helper.addAttachment(fileName2, file2);
        System.out.println(message);
        getJavaMailSender().send(message);
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(Configuration.get("FINALMAILCOUNT")));

            out.write("FINAL BCC SIZE IS::" + BccSize);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(helper.getMimeMessage());

    } catch (MessagingException ex) {
        ex.printStackTrace();
    }

}

From source file:org.kuali.coeus.common.impl.mail.KcEmailServiceImpl.java

public void sendEmailWithAttachments(String from, Set<String> toAddresses, String subject,
        Set<String> ccAddresses, Set<String> bccAddresses, String body, boolean htmlMessage,
        List<EmailAttachment> attachments) {

    if (mailSender != null) {
        if (CollectionUtils.isEmpty(toAddresses) && CollectionUtils.isEmpty(ccAddresses)
                && CollectionUtils.isEmpty(bccAddresses)) {
            return;
        }//from  w w  w  .  j a  v  a  2  s .  co m

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;

        try {
            helper = new MimeMessageHelper(message, true, DEFAULT_ENCODING);
            helper.setFrom(from);

            if (StringUtils.isNotBlank(subject)) {
                helper.setSubject(subject);
            } else {
                LOG.warn("Sending message with empty subject.");
            }

            if (isEmailTestEnabled()) {
                helper.setText(getTestMessageBody(body, toAddresses, ccAddresses, bccAddresses), true);
                String toAddress = getEmailNotificationTestAddress();
                if (StringUtils.isNotBlank(getEmailNotificationTestAddress())) {
                    helper.addTo(toAddress);
                }
            } else {
                helper.setText(body, htmlMessage);
                if (CollectionUtils.isNotEmpty(toAddresses)) {
                    for (String toAddress : toAddresses) {
                        try {
                            helper.addTo(toAddress);
                        } catch (Exception ex) {
                            LOG.warn("Could not set to address:", ex);
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(ccAddresses)) {
                    for (String ccAddress : ccAddresses) {
                        try {
                            helper.addCc(ccAddress);
                        } catch (Exception ex) {
                            LOG.warn("Could not set to address:", ex);
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(bccAddresses)) {
                    for (String bccAddress : bccAddresses) {
                        try {
                            helper.addBcc(bccAddress);
                        } catch (Exception ex) {
                            LOG.warn("Could not set to address:", ex);
                        }
                    }
                }
            }

            if (CollectionUtils.isNotEmpty(attachments)) {
                for (EmailAttachment attachment : attachments) {
                    try {
                        helper.addAttachment(attachment.getFileName(),
                                new ByteArrayResource(attachment.getContents()), attachment.getMimeType());
                    } catch (Exception ex) {
                        LOG.warn("Could not set to address:", ex);
                    }
                }
            }
            executorService.execute(() -> mailSender.send(message));

        } catch (MessagingException ex) {
            LOG.error("Failed to create mime message helper.", ex);
        }
    } else {
        LOG.info(
                "Failed to send email due to inability to obtain valid email mailSender, please check your configuration.");
    }
}

From source file:org.kuali.kra.service.impl.KcEmailServiceImpl.java

public void sendEmailWithAttachments(String from, Set<String> toAddresses, String subject,
        Set<String> ccAddresses, Set<String> bccAddresses, String body, boolean htmlMessage,
        List<EmailAttachment> attachments) {
    JavaMailSender sender = createSender();

    if (sender != null) {
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = null;

        try {/*from   w ww  .j  a v  a  2  s  .  co  m*/
            helper = new MimeMessageHelper(message, true, DEFAULT_ENCODING);
            helper.setFrom(from);

            if (CollectionUtils.isNotEmpty(toAddresses)) {
                for (String toAddress : toAddresses) {
                    helper.addTo(toAddress);
                }
            }

            if (StringUtils.isNotBlank(subject)) {
                helper.setSubject(subject);
            } else {
                LOG.warn("Sending message with empty subject.");
            }

            helper.setText(body, htmlMessage);

            if (CollectionUtils.isNotEmpty(ccAddresses)) {
                for (String ccAddress : ccAddresses) {
                    helper.addCc(ccAddress);
                }
            }

            if (CollectionUtils.isNotEmpty(bccAddresses)) {
                for (String bccAddress : bccAddresses) {
                    helper.addBcc(bccAddress);
                }
            }

            if (CollectionUtils.isNotEmpty(attachments)) {
                for (EmailAttachment attachment : attachments) {
                    helper.addAttachment(attachment.getFileName(),
                            new ByteArrayResource(attachment.getContents()), attachment.getMimeType());
                }
            }

            sender.send(message);
        } catch (MessagingException ex) {
            LOG.error("Failed to create mime message helper.", ex);
        } catch (Exception e) {
            LOG.error("Failed to send email.", e);
        }
    } else {
        LOG.info(
                "Failed to send email due to inability to obtain valid email sender, please check your configuration.");
    }
}

From source file:siddur.solidtrust.wok.WokController.java

@Scheduled(cron = "0 5 1 2 * ?") //01:05 2th monthly
@RequestMapping("notify")
public void sendMail() throws Exception {
    Calendar today = Calendar.getInstance();
    int year = today.get(Calendar.YEAR);
    int month = today.get(Calendar.MONTH);
    String filename = year + "-" + month + ".xlsx";
    File file = new File(FileSystemUtil.getWokDir(), filename);
    generateFile(year, month, file);//w  w w  .  j  a v a2 s.  c  o  m

    log4j.info("Send email for WOK records: " + file.getName());
    MimeMessage message = mailSender.createMimeMessage();

    // use the true flag to indicate you need a multipart message
    MimeMessageHelper helper = new MimeMessageHelper(message, true);

    helper.setFrom("gbg1_spsms_gtrak@pactera-pgs-mail.chinacloudapp.cn", "Solidtrust Admin");
    helper.setTo(SolidtrustConstants.WOK_EMAIL);
    helper.addCc(SolidtrustConstants.BEN_EMAIL);
    helper.addCc(SolidtrustConstants.MY_EMAIL);
    helper.setSubject(MessageFormat.format("WOK[{0}]", (year + "-" + month)));

    // use the true flag to indicate the text included is HTML
    helper.setText("<html><body>Here is WOK data of last month. Thanks.</body></html>", true);

    // let's include the infamous windows Sample file (this time copied to c:/)
    FileSystemResource res = new FileSystemResource(file);
    helper.addAttachment(file.getName(), res);

    mailSender.send(message);
}