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

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

Introduction

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

Prototype

public MimeMessageHelper(MimeMessage mimeMessage, int multipartMode, @Nullable String encoding)
        throws MessagingException 

Source Link

Document

Create a new MimeMessageHelper for the given MimeMessage, in multipart mode (supporting alternative texts, inline elements and attachments) if requested.

Usage

From source file:org.wallride.service.UserService.java

@CacheEvict(value = WallRideCacheConfiguration.USER_CACHE, allEntries = true)
public UserInvitation inviteAgain(UserInvitationResendRequest form, BindingResult result,
        AuthorizedUser authorizedUser) throws MessagingException {
    LocalDateTime now = LocalDateTime.now();

    UserInvitation invitation = userInvitationRepository.findOneForUpdateByToken(form.getToken());
    invitation.setExpiredAt(now.plusHours(72));
    invitation.setUpdatedAt(now);/*from www .  j a  va2s.  co m*/
    invitation.setUpdatedBy(authorizedUser.toString());
    invitation = userInvitationRepository.saveAndFlush(invitation);

    Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
    String websiteTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());
    String signupLink = ServletUriComponentsBuilder.fromCurrentContextPath().path("/_admin/signup")
            .queryParam("token", invitation.getToken()).buildAndExpand().toString();

    final Context ctx = new Context(LocaleContextHolder.getLocale());
    ctx.setVariable("websiteTitle", websiteTitle);
    ctx.setVariable("authorizedUser", authorizedUser);
    ctx.setVariable("signupLink", signupLink);
    ctx.setVariable("invitation", invitation);

    final MimeMessage mimeMessage = mailSender.createMimeMessage();
    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
    message.setSubject(MessageFormat.format(
            messageSourceAccessor.getMessage("InvitationMessageTitle", LocaleContextHolder.getLocale()),
            authorizedUser.toString(), websiteTitle));
    message.setFrom(authorizedUser.getEmail());
    message.setTo(invitation.getEmail());

    final String htmlContent = templateEngine.process("user-invite", ctx);
    message.setText(htmlContent, true); // true = isHtml

    mailSender.send(mimeMessage);

    return invitation;
}

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

public void testEncodedFromToAddresses() throws Exception {
    // RFC1342//from   w  w w .  j a va  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.broadleafcommerce.common.email.service.message.MessageCreator.java

public MimeMessagePreparator buildMimeMessagePreparator(final Map<String, Object> props) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @Override/* w  ww .ja  v a 2  s  .  c  o  m*/
        public void prepare(MimeMessage mimeMessage) throws Exception {
            EmailTarget emailUser = (EmailTarget) props.get(EmailPropertyType.USER.getType());
            EmailInfo info = (EmailInfo) props.get(EmailPropertyType.INFO.getType());
            boolean isMultipart = CollectionUtils.isNotEmpty(info.getAttachments());
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, info.getEncoding());
            message.setTo(emailUser.getEmailAddress());
            message.setFrom(info.getFromAddress());
            message.setSubject(info.getSubject());
            if (emailUser.getBCCAddresses() != null && emailUser.getBCCAddresses().length > 0) {
                message.setBcc(emailUser.getBCCAddresses());
            }
            if (emailUser.getCCAddresses() != null && emailUser.getCCAddresses().length > 0) {
                message.setCc(emailUser.getCCAddresses());
            }
            String messageBody = info.getMessageBody();
            if (messageBody == null) {
                messageBody = buildMessageBody(info, props);
            }
            message.setText(messageBody, true);
            for (Attachment attachment : info.getAttachments()) {
                ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment.getData(),
                        attachment.getMimeType());
                message.addAttachment(attachment.getFilename(), dataSource);
            }
        }
    };
    return preparator;

}

From source file:org.emmanet.controllers.requestsUpdateInterfaceFormController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws ServletException, Exception {
    model.put("BASEURL", BASEURL);
    System.out.println("BASEURL VALUE FROM MODEL IS::" + model.get("BASEURL"));
    WebRequestsDAO webRequest = (WebRequestsDAO) command;

    if (!request.getParameter("noTAinfo").equals("true")) {
        String panelDecision = webRequest.getTa_panel_decision();

        String applicationType = webRequest.getApplication_type();

        if (panelDecision.equals("yes") || panelDecision.equals("no") && applicationType.contains("ta")) {
            //check if mail already sent by checking notes for string
            if (!webRequest.getNotes().contains("TA mail sent")) {

                //Decision has been made therefore decision mails should be triggered
                //SimpleMailMessage msg = getSimpleMailMessage();
                MimeMessage msg = getJavaMailSender().createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
                String content = "";
                String toAddress = webRequest.getSci_e_mail();
                // msg.setTo(toAddress);
                helper.setTo(toAddress);
                helper.setFrom(getFromAddress());

                String[] ccs = getCc();
                List lCc = new ArrayList();
                for (int i = 0; i < ccs.length; i++) {
                    //add configurated cc addresses to list
                    String CcElement = ccs[i];
                    lCc.add(CcElement);/*from w ww  .  j a va 2  s .  c o  m*/
                }
                lCc.add(webRequest.getCon_e_mail());
                List ccCentre = wr.ccArchiveMailAddresses("" + webRequest.getStr_id_str(), "strains");

                Object[] o = null;
                Iterator it = ccCentre.iterator();
                while (it.hasNext()) {
                    o = (Object[]) it.next();
                    lCc.add(o[1].toString());
                }
                String[] ar = new String[lCc.size()];
                for (int i = 0; i < lCc.size(); i++) {
                    Object oo = lCc.get(i);
                    ar[i] = oo.toString();
                    System.out.println(oo.toString());
                }

                String[] bccs = getBcc();
                //msg.
                helper.setBcc(bccs);

                //msg.
                helper.setCc(ar);

                /*  format date string */
                String date = webRequest.getTimestamp().toString();
                String yyyy = date.substring(0, 4);
                String MM = date.substring(5, 7);
                String dd = date.substring(8, 10);

                date = dd + "-" + MM + "-" + yyyy;
                model.put("name", webRequest.getSci_firstname() + " " + webRequest.getSci_surname());
                model.put("emmaid", webRequest.getStrain_id().toString());
                model.put("strainname", webRequest.getStrain_name());
                model.put("timestamp", date);
                model.put("sci_title", webRequest.getSci_title());
                model.put("sci_firstname", webRequest.getSci_firstname());
                model.put("sci_surname", webRequest.getSci_surname());
                model.put("sci_e_mail", webRequest.getSci_e_mail());
                model.put("strain_id", webRequest.getStrain_id());
                model.put("strain_name", webRequest.getStrain_name());
                model.put("common_name_s", webRequest.getCommon_name_s());
                model.put("req_material", webRequest.getReq_material());
                //new mta file inclusion
                model.put("requestID", webRequest.getId_req());
                model.put("BASEURL", BASEURL);
                StrainsManager sm = new StrainsManager();
                StrainsDAO sd = sm.getStrainByID(webRequest.getStr_id_str());
                if (!webRequest.getLab_id_labo().equals("4")) {
                    /*
                     * FOR LEGAL REASONS MTA FILE AND USAGE TEXT SHOULD NOT BE SHOWN FOR MRC STOCK.
                     * MRC WILL SEND MTA SEPARATELY (M.FRAY EMMA IT MEETING 28-29 OCT 2010)
                     */
                    model.put("mtaFile", sd.getMta_file());
                }
                //########################################################            

                String rtoolsID = "";
                List rtools = wr.strainRToolID(webRequest.getStr_id_str());
                it = rtools.iterator();
                while (it.hasNext()) {
                    Object oo = it.next();
                    rtoolsID = oo.toString();
                }

                model.put("rtoolsID", rtoolsID);
                //TEMPLATE SELECTION

                if (panelDecision.equals("yes")) {
                    //we need to send a mail
                    if (webRequest.getApplication_type().contains("ta_")) {
                        System.out.println(getTemplatePath() + getTaOrRequestYesTemplate());
                        content = VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(),
                                getTemplatePath() + getTaOrRequestYesTemplate(), model);
                    }
                }
                /* webRequest.getTa_panel_decision().equals("no") */
                if (panelDecision.equals("no")) {
                    System.out.println("panel decision == no ==");
                    if (applicationType.equals("ta_or_request")) {
                        System.out.println("path to template for ta_or_req and no==" + getTemplatePath()
                                + getTaOrRequestNoTemplate());
                        content = VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(),
                                getTemplatePath() + getTaOrRequestNoTemplate(), model);
                    }
                    if (applicationType.equals("ta_only")) {
                        //TODO IF NO AND TA_ONLY THEN REQ_STATUS=CANC
                        webRequest.setReq_status("CANC");
                        System.out.println("path to template for ta_only and no==" + getTemplatePath()
                                + getTaOnlyNoTemplate());
                        content = VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(),
                                getTemplatePath() + getTaOnlyNoTemplate(), model);
                    }
                }

                //send message
                //msg.
                helper.setSubject(
                        msgSubject + webRequest.getStrain_name() + "(" + webRequest.getStrain_id() + ")");
                //msg.
                helper.setText(content);

                //###/add mta file if associated with strain id
                String mtaFile = "";
                mtaFile = (new StringBuilder()).append(mtaFile).append(sd.getMta_file()).toString();

                if (mtaFile != null || model.get("mtaFile").toString().equals("")) {
                    FileSystemResource fileMTA = new FileSystemResource(new File(getPathToMTA() + mtaFile));
                    //need to check for a valid mta filename use period extension separator, all mtas are either .doc or .pdf
                    if (fileMTA.exists() && fileMTA.toString().contains(".")) {
                        //M Hagn decided now to not send an MTA at this point as users should have already received one. Was confusing users to receive another philw@ebi.ac.uk 05042011
                        //helper.addAttachment(model.get("mtaFile").toString(), fileMTA);
                    }
                }
                System.out.println("Rtools=" + model.get("rtoolsID") + " and labID=" + model.get("labID"));
                if (request.getParameter("TEST") != null) {
                    // TESTER SUBMITTED EMAIL ADDRESS
                    //msg.
                    helper.setTo(request.getParameter("TEST"));
                    //msg.
                    helper.setCc(request.getParameter("TEST"));
                    String Ccs = "";
                    for (int i = 0; i < ar.length; i++) {
                        Ccs = Ccs + ", " + ar[i];
                    }
                    //msg.
                    helper.setText("TEST EMAIL, LIVE EMAIL SENT TO " + toAddress + " CC'D TO :\n\n " + Ccs
                            + " LIVE MESSAGE TEXT FOLLOWS BELOW::\n\n" + content);
                }
                if (!toAddress.equals("")) {
                    //Set notes to contain ta mail sent trigger
                    String notes = webRequest.getNotes();
                    notes = notes + "TA mail sent";
                    webRequest.setNotes(notes);
                }
                getJavaMailSender().send(msg);
            }
        }
    }

    if (request.getParameter("fSourceID") != null || !request.getParameter("fSourceID").equals("")) {
        //save requestfunding source ID
        boolean saveOnly = false;
        int sour_id = Integer.parseInt(request.getParameter("fSourceID"));
        int srcID = Integer.parseInt(webRequest.getId_req());
        System.out.println("fSourceID==" + srcID);
        srd = wr.getReqSourcesByID(srcID);//sm.getSourcesByID(srcID);

        //  
        try {
            srd.getSour_id();//ssd.getSour_id();
            srd.setSour_id(sour_id);
        } catch (NullPointerException np) {
            srd = new Sources_RequestsDAO();
            int reqID = Integer.parseInt(webRequest.getId_req());

            srd.setReq_id_req(reqID);

            srd.setSour_id(sour_id);
            //save only here not save or update
            saveOnly = true;

        }

        if (saveOnly) {
            wr.saveOnly(srd);
            System.out.println("THIS IS NOW SAVED:: SAVEONLY");
        } else if (!saveOnly) {
            //save or update
            System.out.println("SAVEORUPDATEONLY + value is.." + srd);
            wr.save(srd);
            System.out.println("THIS IS NOW SAVED:: SAVEORUPDATEONLY");
        }

    }

    wr.saveRequest(webRequest);
    request.getSession().setAttribute("message",
            getMessageSourceAccessor().getMessage("Message", "Your update submitted successfully"));

    if (webRequest.getProjectID().equals("3") && webRequest.getLab_id_labo().equals("1961")) {
        //OK this is a Sanger/Eucomm strain and could be subject to charging so may need to send xml
        if (request.getParameter("currentReqStatus").contains("PR")
                && webRequest.getReq_status().equals("SHIP")) {

            //status changed to shipped from a non cancelled request so subject to a charge
            model.put("name", webRequest.getSci_firstname() + " " + webRequest.getSci_surname());
            model.put("emmaid", webRequest.getStrain_id().toString());
            model.put("strainname", webRequest.getStrain_name());
            model.put("timestamp", webRequest.getTimestamp());
            model.put("ftimestamp", webRequest.getFtimestamp());
            model.put("sci_title", webRequest.getSci_title());
            model.put("sci_firstname", webRequest.getSci_firstname());
            model.put("sci_surname", webRequest.getSci_surname());
            model.put("sci_e_mail", webRequest.getSci_e_mail());
            model.put("sci_phone", webRequest.getSci_phone());
            model.put("sci_fax", webRequest.getSci_fax());
            model.put("con_title", webRequest.getCon_title());
            model.put("con_firstname", webRequest.getCon_firstname());
            model.put("con_surname", webRequest.getCon_surname());
            model.put("con_e_mail", webRequest.getCon_e_mail());
            model.put("con_phone", webRequest.getCon_phone());
            model.put("con_fax", webRequest.getCon_fax());
            model.put("con_institution", webRequest.getCon_institution());
            model.put("con_dept", webRequest.getCon_dept());
            model.put("con_addr_1", webRequest.getCon_addr_1());
            model.put("con_addr_2", webRequest.getCon_addr_2());
            model.put("con_province", webRequest.getCon_province());
            model.put("con_town", webRequest.getCon_town());
            model.put("con_postcode", webRequest.getCon_postcode());
            model.put("con_country", webRequest.getCon_country());

            //billing details

            if (!webRequest.getRegister_interest().equals("1")) {
                model.put("PO_ref", webRequest.getPO_ref());
                model.put("bil_title", webRequest.getBil_title());
                model.put("bil_firstname", webRequest.getBil_firstname());
                model.put("bil_surname", webRequest.getBil_surname());
                model.put("bil_e_mail", webRequest.getBil_e_mail());
                model.put("bil_phone", webRequest.getBil_phone());
                model.put("bil_fax", webRequest.getBil_fax());
                model.put("bil_institution", webRequest.getBil_institution());
                model.put("bil_dept", webRequest.getBil_dept());
                model.put("bil_addr_1", webRequest.getBil_addr_1());
                model.put("bil_addr_2", webRequest.getBil_addr_2());
                model.put("bil_province", webRequest.getBil_province());
                model.put("bil_town", webRequest.getBil_town());
                model.put("bil_postcode", webRequest.getBil_postcode());
                model.put("bil_country", webRequest.getBil_country());
                model.put("bil_vat", webRequest.getBil_vat());
            }
            //end biling details

            model.put("strain_id", webRequest.getStrain_id());
            model.put("strain_name", escapeXml(webRequest.getStrain_name()));
            model.put("common_name_s", webRequest.getCommon_name_s());
            model.put("req_material", webRequest.getReq_material());
            model.put("live_animals", webRequest.getLive_animals());
            model.put("frozen_emb", webRequest.getFrozen_emb());
            model.put("frozen_spe", webRequest.getFrozen_spe());
            // TA application details
            model.put("application_type", webRequest.getApplication_type());
            model.put("ta_eligible", webRequest.getEligible_country());

            if (webRequest.getApplication_type().contains("ta")) {
                model.put("ta_proj_desc", webRequest.getProject_description());
                model.put("ta_panel_sub_date", webRequest.getTa_panel_sub_date());
                model.put("ta_panel_decision_date", webRequest.getTa_panel_decision_date());
                model.put("ta_panel_decision", webRequest.getTa_panel_decision());
            } else {
                model.put("ta_proj_desc", "");
                model.put("ta_panel_sub_date", "");
                model.put("ta_panel_decision_date", "");
                model.put("ta_panel_decision", "");
            }
            model.put("ROI", webRequest.getRegister_interest());

            model.put("europhenome", webRequest.getEurophenome());
            model.put("wtsi_mouse_portal", webRequest.getWtsi_mouse_portal());

            //now create xml file

            String xmlFileContent = VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(),
                    "org/emmanet/util/velocitytemplates/requestXml-Template.vm", model);

            File file = new File(Configuration.get("sangerLineDistribution"));
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
            out.write(xmlFileContent);
            out.close();

            //email file now
            MimeMessage message = getJavaMailSender().createMimeMessage();

            try {
                MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
                helper.setReplyTo("emma@infrafrontier.eu");
                helper.setFrom("emma@infrafrontier.eu");
                helper.setBcc(bcc);
                helper.setTo(sangerLineDistEmail);
                helper.setSubject("Sanger Line Distribution " + webRequest.getStrain_id());
                helper.addAttachment("sangerlinedistribution.xml", file);
                getJavaMailSender().send(message);
            } catch (MessagingException ex) {
                ex.printStackTrace();
            }
        }
    }
    System.out.println("BASEURL VALUE FROM MODEL IS::" + model.get("BASEURL"));
    return new ModelAndView(
            "redirect:requestsUpdateInterface.emma?Edit=" + request.getParameter("Edit").toString()
                    + "&strainID=" + request.getParameter("strainID").toString() + "&archID="
                    + request.getParameter("archID").toString());
}

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);//www.j  a  v a 2  s .  com
    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;
        }/*  w  w  w  . j a  va 2  s .  c om*/

        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.ja v  a 2s.  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.");
    }
}

From source file:org.openremote.modeler.service.impl.UserServiceImpl.java

/**
 * {@inheritDoc}/*from   w ww . jav a2s  . c o m*/
 */
public boolean sendRegisterActivationEmail(final User user) {
    if (user == null || user.getOid() == 0 || StringUtils.isEmpty(user.getEmail())
            || StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
        return false;
    }

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        @SuppressWarnings("unchecked")
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            message.setSubject("OpenRemote Boss 2.0 Account Registration Confirmation");
            message.setTo(user.getEmail());
            message.setFrom(mailSender.getUsername());
            Map model = new HashMap();
            model.put("user", user);
            String rpwd = user.getRawPassword();
            StringBuffer maskPwd = new StringBuffer();
            maskPwd.append(rpwd.substring(0, 1));
            for (int i = 0; i < rpwd.length() - 2; i++) {
                maskPwd.append("*");
            }
            maskPwd.append(rpwd.substring(rpwd.length() - 1));
            model.put("maskPassword", maskPwd.toString());
            model.put("webapp", configuration.getWebappServerRoot());
            model.put("aid", new Md5PasswordEncoder().encodePassword(user.getUsername(), user.getPassword()));
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    Constants.REGISTRATION_ACTIVATION_EMAIL_VM_NAME, "UTF-8", model);
            message.setText(text, true);
        }
    };
    try {
        this.mailSender.send(preparator);
        log.info("Sent 'Modeler Account Registration Confirmation' email to " + user.getEmail());
        return true;
    } catch (MailException e) {
        log.error("Can't send 'Modeler Account Registration Confirmation' email", e);
        return false;
    }
}

From source file:org.openremote.modeler.service.impl.UserServiceImpl.java

public boolean sendInvitation(final User invitee, final User currentUser) {
    if (invitee == null || invitee.getOid() == 0 || StringUtils.isEmpty(invitee.getEmail())) {
        return false;
    }//from  w w  w.  ja v a  2 s. c  o m

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        @SuppressWarnings("unchecked")
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            message.setSubject("Invitation to Share an OpenRemote Boss 2.0 Account");
            message.setTo(invitee.getEmail());
            message.setFrom(mailSender.getUsername());
            Map model = new HashMap();
            model.put("uid", invitee.getOid());
            model.put("role", invitee.getRole());
            model.put("cid", currentUser.getOid());
            model.put("host", currentUser.getEmail());
            model.put("webapp", configuration.getWebappServerRoot());
            model.put("aid",
                    new Md5PasswordEncoder().encodePassword(invitee.getEmail(), currentUser.getPassword()));
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    Constants.REGISTRATION_INVITATION_EMAIL_VM_NAME, "UTF-8", model);
            message.setText(text, true);
        }
    };
    try {
        this.mailSender.send(preparator);
        log.info("Sent 'Modeler Account Invitation' email to " + invitee.getEmail());
        return true;
    } catch (MailException e) {
        log.error("Can't send 'Modeler Account Invitation' email", e);
        return false;
    }
}

From source file:org.openremote.modeler.service.impl.UserServiceImpl.java

public User forgetPassword(String username) {
    final User user = genericDAO.getByNonIdField(User.class, "username", username);
    final String passwordToken = UUID.randomUUID().toString();

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        @SuppressWarnings("unchecked")
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            message.setSubject("OpenRemote Password Assistance");
            message.setTo(user.getEmail());
            message.setFrom(mailSender.getUsername());
            Map model = new HashMap();
            model.put("webapp", configuration.getWebappServerRoot());
            model.put("username", user.getUsername());
            model.put("uid", user.getOid());
            model.put("aid", passwordToken);
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    Constants.FORGET_PASSWORD_EMAIL_VM_NAME, "UTF-8", model);
            message.setText(text, true);
        }/*from  ww  w  . j  a  v a 2  s  . com*/
    };
    try {
        this.mailSender.send(preparator);
        log.info("Sent 'Reset password' email to " + user.getEmail());
        user.setToken(passwordToken);
        updateUser(user);
        return user;
    } catch (MailException e) {
        log.error("Can't send 'Reset password' email", e);
        return null;
    }
}