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

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

Introduction

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

Prototype

public void addTo(String to) throws MessagingException 

Source Link

Usage

From source file:org.jasig.ssp.util.importer.job.report.ReportGenerator.java

private void sendEmail(JobExecution jobExecution, String report) {

    final MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    final MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
    String[] recipients = emailRecipients.split(",");
    String EOL = System.getProperty("line.separator");

    try {/*from   w w w.j  av a2 s  .c o m*/
        for (String recipient : recipients) {
            mimeMessageHelper.addTo(recipient);

            if (!StringUtils.isEmpty(replyTo)) {
                mimeMessageHelper.setReplyTo(replyTo);
            }
            mimeMessageHelper.setSubject("Data Import Report for SSP Instance: " + batchTitle + " JobId: "
                    + jobExecution.getJobId());
            mimeMessageHelper.setText(report);
            javaMailSender.send(mimeMessage);

        }
        logger.info("Report emailed" + EOL);
    } catch (MessagingException e) {
        logger.error(e.toString());
    }
    ;
}

From source file:business.services.MailService.java

public void notifyLab(@NotNull LabRequestRepresentation labRequest) {
    log.info("Notify lab for lab request " + labRequest.getId() + ".");

    Lab lab = labRequest.getLab();//from  ww w  .  j  a v  a 2s.  co m
    if (lab.getEmailAddresses() == null || lab.getEmailAddresses().isEmpty()) {
        log.warn("No email address set for lab " + lab.getNumber());
        return;
    }
    String recipients = String.join(", ", lab.getEmailAddresses());
    log.info("Sending notification to " + recipients);
    try {
        MimeMessageHelper message = new MimeMessageHelper(mailSender.createMimeMessage());
        for (String email : lab.getEmailAddresses()) {
            message.addTo(email);
        }
        message.setFrom(getFrom(), fromName);
        message.setReplyTo(replyAddress, replyName);
        message.setSubject(String.format("PALGA-verzoek aan laboratorium, aanvraagnummer: %s",
                labRequest.getLabRequestCode()));
        String labRequestLink = getLink("/#/lab-request/view/" + labRequest.getId());
        String body = String.format(labNotificationTemplate, labRequestLink, // %1
                labRequest.getLabRequestCode(), // %2
                labRequest.getRequest().getTitle(), // %3
                labRequest.getRequesterName(), // %4
                labRequest.getRequest().getPathologistName() == null ? ""
                        : labRequest.getRequest().getPathologistName(), // %5
                labRequest.getRequesterLab().getName() // %6
        );
        message.setText(body);
        mailSender.send(message.getMimeMessage());
    } catch (MessagingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    }
}

From source file:cdr.forms.EmailNotificationHandler.java

@Override
public void notifyError(Deposit deposit, DepositResult result) {

    Form form = deposit.getForm();//from   w ww .  j ava  2 s.  c  om
    String formId = deposit.getFormId();
    String depositorEmail = deposit.getReceiptEmailAddress();
    List<String> recipients = deposit.getAllDepositNoticeToEmailAddresses();

    // put data into the model
    HashMap<String, Object> model = new HashMap<String, Object>();
    model.put("deposit", deposit);
    model.put("form", form);
    model.put("formId", formId);
    model.put("result", result);
    model.put("depositorEmail", depositorEmail);
    model.put("siteUrl", this.getSiteUrl());
    model.put("siteName", this.getSiteName());
    model.put("receivedDate", new Date(System.currentTimeMillis()));
    StringWriter htmlsw = new StringWriter();
    StringWriter textsw = new StringWriter();

    try {
        depositErrorHtmlTemplate.process(model, htmlsw);
        depositErrorTextTemplate.process(model, textsw);
    } catch (TemplateException e) {
        LOG.error("cannot process email template", e);
        return;
    } catch (IOException e) {
        LOG.error("cannot process email template", e);
        return;
    }

    try {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED);

        if (administratorAddress != null && administratorAddress.trim().length() > 0) {
            message.addTo(this.administratorAddress);
        }

        for (String recipient : recipients) {
            message.addTo(recipient);
        }

        message.setSubject("Deposit Error for " + form.getTitle());
        message.setFrom(this.getFromAddress());
        message.setText(textsw.toString(), htmlsw.toString());
        this.mailSender.send(mimeMessage);
    } catch (MessagingException e) {
        LOG.error("problem sending error notification message", e);
        return;
    }

}

From source file:dk.nsi.haiba.epimibaimporter.email.EmailSender.java

private void sendText(final String subject, final String nonHtml) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        @Override//from  w  ww  .j  av  a  2 s . c  o m
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setValidateAddresses(true);

            String[] split = to_commaseparated.split(",");
            for (String emailAddress : split) {
                emailAddress = emailAddress.trim();
                try {
                    log.trace("adding " + emailAddress);
                    messageHelper.addTo(emailAddress);
                    log.trace("added " + emailAddress);
                } catch (MessagingException e) {
                    log.error("unable to parse email address from " + emailAddress, e);
                }
            }
            messageHelper.setFrom(from);
            messageHelper.setSubject(subject);
            messageHelper.setText(nonHtml, false);
        }
    };
    javaMailSender.send(preparator);
}

From source file:edu.unc.lib.dl.services.MailNotifier.java

public void sendIngestSuccessNotice(IngestProperties props, int ingestedCount) {
    String html = null, text = null;
    boolean logEmail = true;
    MimeMessage mimeMessage = null;/*from   ww w. ja va  2 s.  c o  m*/
    try {
        Template htmlTemplate = this.freemarkerConfiguration.getTemplate("IngestSuccessHtml.ftl",
                Locale.getDefault(), "utf-8");
        Template textTemplate = this.freemarkerConfiguration.getTemplate("IngestSuccessText.ftl",
                Locale.getDefault(), "utf-8");

        // put data into the model
        HashMap<String, Object> model = new HashMap<String, Object>();
        model.put("numberOfObjects", new Integer(ingestedCount));
        model.put("irBaseUrl", this.irBaseUrl);
        List tops = new ArrayList();
        for (ContainerPlacement p : props.getContainerPlacements().values()) {
            HashMap om = new HashMap();
            om.put("pid", p.pid.getPid());
            om.put("label", p.label);
            tops.add(om);
        }
        model.put("tops", tops);

        StringWriter sw = new StringWriter();
        htmlTemplate.process(model, sw);
        html = sw.toString();
        sw = new StringWriter();
        textTemplate.process(model, sw);
        text = sw.toString();
    } catch (IOException e1) {
        throw new Error("Unable to load email template for Ingest Success", e1);
    } catch (TemplateException e) {
        throw new Error("There was a problem loading FreeMarker templates for email notification", e);
    }

    try {
        if (log.isDebugEnabled() && this.mailSender instanceof JavaMailSenderImpl) {
            ((JavaMailSenderImpl) this.mailSender).getSession().setDebug(true);
        }
        mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED);

        for (String addy : props.getEmailRecipients()) {
            message.addTo(addy);
        }
        message.setSubject("CDR ingest complete");

        message.setFrom(this.getRepositoryFromAddress());
        message.setText(text, html);

        // attach Events XML
        // Document events = new Document(aip.getEventLogger().getAllEvents());
        // message.addAttachment("events.xml", new JDOMStreamSource(events));
        this.mailSender.send(mimeMessage);
        logEmail = false;
    } catch (MessagingException e) {
        log.error("Unable to send ingest success email.", e);
    } catch (RuntimeException e) {
        log.error(e);
    } finally {
        if (mimeMessage != null && logEmail) {
            try {
                mimeMessage.writeTo(System.out);
            } catch (Exception e) {
                log.error("Could not log email message after error.", 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  w  w  w.jav a  2 s  .  c o 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
 */// w  w w .  j av a 2s  .  c  om
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:edu.unc.lib.dl.services.MailNotifier.java

/**
 * @param e//from ww w.  j  a  v  a2  s.c o m
 * @param user
 */
public void sendIngestFailureNotice(Throwable ex, IngestProperties props) {
    String html = null, text = null;
    MimeMessage mimeMessage = null;
    boolean logEmail = true;
    try {
        // create templates
        Template htmlTemplate = this.freemarkerConfiguration.getTemplate("IngestFailHtml.ftl",
                Locale.getDefault(), "utf-8");
        Template textTemplate = this.freemarkerConfiguration.getTemplate("IngestFailText.ftl",
                Locale.getDefault(), "utf-8");

        if (log.isDebugEnabled() && this.mailSender instanceof JavaMailSenderImpl) {
            ((JavaMailSenderImpl) this.mailSender).getSession().setDebug(true);
        }

        // create mail message
        mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED);

        // put data into the model
        HashMap<String, Object> model = new HashMap<String, Object>();
        model.put("irBaseUrl", this.irBaseUrl);
        /*         List<ContainerPlacement> tops = new ArrayList<ContainerPlacement>();
                 tops.addAll(props.getContainerPlacements().values());
                 model.put("tops", tops);*/

        if (ex != null && ex.getMessage() != null) {
            model.put("message", ex.getMessage());
        } else if (ex != null) {
            model.put("message", ex.toString());
        } else {
            model.put("message", "No exception or error message available.");
        }

        // specific exception processing
        if (ex instanceof FilesDoNotMatchManifestException) {
            model.put("FilesDoNotMatchManifestException", ex);
        } else if (ex instanceof InvalidMETSException) {
            model.put("InvalidMETSException", ex);
            InvalidMETSException ime = (InvalidMETSException) ex;
            if (ime.getSvrl() != null) {
                Document jdomsvrl = ((InvalidMETSException) ex).getSvrl();
                DOMOutputter domout = new DOMOutputter();
                try {
                    org.w3c.dom.Document svrl = domout.output(jdomsvrl);
                    model.put("svrl", NodeModel.wrap(svrl));

                    // also dump SVRL to attachment
                    message.addAttachment("schematron-output.xml", new JDOMStreamSource(jdomsvrl));
                } catch (JDOMException e) {
                    throw new Error(e);
                }
            }
        } else if (ex instanceof METSParseException) {
            log.debug("putting MPE in the model");
            model.put("METSParseException", ex);
        } else {
            log.debug("IngestException without special email treatment", ex);
        }

        // attach error xml if available
        if (ex instanceof IngestException) {
            IngestException ie = (IngestException) ex;
            if (ie.getErrorXML() != null) {
                message.addAttachment("error.xml", new JDOMStreamSource(ie.getErrorXML()));
            }
        }

        model.put("user", props.getSubmitter());
        model.put("irBaseUrl", this.irBaseUrl);

        StringWriter sw = new StringWriter();
        htmlTemplate.process(model, sw);
        html = sw.toString();
        sw = new StringWriter();
        textTemplate.process(model, sw);
        text = sw.toString();

        // Addressing: to initiator if a person, otherwise to all members of
        // admin group
        if (props.getEmailRecipients() != null) {
            for (String r : props.getEmailRecipients()) {
                message.addTo(r);
            }
        }
        message.addTo(this.getAdministratorAddress(), "CDR Administrator");
        message.setSubject("CDR ingest failed");
        message.setFrom(this.getRepositoryFromAddress());
        message.setText(text, html);

        // attach Events XML
        // if (aip != null) {
        // /message.addAttachment("events.xml", new JDOMStreamSource(aip.getEventLogger().getAllEvents()));
        // }
        this.mailSender.send(mimeMessage);
        logEmail = false;
    } catch (MessagingException e) {
        log.error("Unable to send ingest fail email.", e);
    } catch (MailSendException e) {
        log.error("Unable to send ingest fail email.", e);
    } catch (UnsupportedEncodingException e) {
        log.error("Unable to send ingest fail email.", e);
    } catch (IOException e1) {
        throw new Error("Unable to load email template for Ingest Failure", e1);
    } catch (TemplateException e) {
        throw new Error("There was a problem loading FreeMarker templates for email notification", e);
    } finally {
        if (mimeMessage != null && logEmail) {
            try {
                mimeMessage.writeTo(System.out);
            } catch (Exception e) {
                log.error("Could not log email message after error.", e);
            }
        }
    }
}

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

public void testEncodedFromToAddresses() throws Exception {
    // RFC1342//from  ww w .  j  a  va2 s .  co 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.apereo.portal.portlets.account.EmailPasswordResetNotificationImpl.java

@Override
public void sendNotification(URL resetUrl, ILocalAccountPerson account, Locale locale) {
    log.debug("Sending password reset instructions to user with url {}", resetUrl.toString());

    try {/*from   w w  w. j  a v a  2 s.c  o m*/
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        String email = (String) account.getAttributeValue(ILocalAccountPerson.ATTR_MAIL);
        String subject = messageSource.getMessage(subjectMessageKey, new Object[] {}, locale);
        String body = formatBody(resetUrl, account, locale);

        helper.addTo(email);
        helper.setText(body, true);
        helper.setSubject(subject);
        helper.setFrom(portalEmailAddress, messageSource.getMessage("portal.name", new Object[] {}, locale));

        log.debug("Sending message to {} from {} subject {}", email, Arrays.toString(message.getFrom()),
                message.getSubject());
        this.mailSender.send(helper.getMimeMessage());

    } catch (Exception e) {
        log.error("Unable to send password reset email", e);
    }
}