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

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

Introduction

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

Prototype

public void addBcc(String bcc) throws MessagingException 

Source Link

Usage

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

@Override
public void sendEmail(EmailBuilder emailBuilder) {

    try {/*from w  w  w.j  av  a2s  . 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: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 {//from   ww w . j a v a  2s.  co m
        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  w w.  j  a  v  a 2 s .  co  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.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.  ja  v  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  a2s  . 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  w w . j  ava2s.  c  o 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.");
    }
}