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

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

Introduction

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

Prototype

public void setSubject(String subject) throws MessagingException 

Source Link

Document

Set the subject of the message, using the correct encoding.

Usage

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

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

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

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

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

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

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

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

From source file:com.mobileman.projecth.business.impl.MailManagerImpl.java

/** 
 * {@inheritDoc}//from   ww w. j  a va2  s  . c  om
 * @see com.mobileman.projecth.business.MailManager#sendTellAFriendMessage(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
 */
@Override
public void sendTellAFriendMessage(final String senderName, final String senderEmail,
        final String receiverEmails, final String body) {
    if (log.isDebugEnabled()) {
        log.debug("sendMessage(" + senderName + ", " + senderEmail + ", " + receiverEmails + ", " + body
                + ") - start");
    }

    if (senderEmail == null || senderEmail.trim().length() == 0) {
        throw new MailException(MailException.Reason.SENDER_EMAIL_MISSING);
    }

    if (receiverEmails == null || receiverEmails.trim().length() == 0) {
        throw new MailException(MailException.Reason.SENDER_EMAIL_MISSING);
    }

    final String[] senderData = { "", "", "" };

    final String[] receivers = receiverEmails.split("[,]");
    for (int i = 0; i < receivers.length; i++) {
        final int idx = i;
        MimeMessagePreparator preparator = new MimeMessagePreparator() {

            /**
             * {@inheritDoc}
             * @see org.springframework.mail.javamail.MimeMessagePreparator#prepare(javax.mail.internet.MimeMessage)
             */
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                if (log.isDebugEnabled()) {
                    log.debug("$MimeMessagePreparator.prepare(MimeMessage) - start"); //$NON-NLS-1$
                }

                MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, EMAIL_ENCODING);
                messageHelper.setSentDate(new Date());

                Map<String, Object> model = new HashMap<String, Object>();
                model.put("body-text", body);
                String htmlMessage = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                        "tell-a-friend-email-body.vm", model);
                String textMessage = HTMLTextParser.htmlToText(htmlMessage);
                messageHelper.setText(textMessage, htmlMessage);
                senderData[0] = htmlMessage;
                senderData[1] = textMessage;
                senderData[2] = "Mitteilung von projecth";

                messageHelper.setSubject(senderData[2]);
                messageHelper.setTo(receivers[idx]);
                messageHelper.setFrom(getSystemAdminEmail());

                if (log.isDebugEnabled()) {
                    log.debug("$MimeMessagePreparator.prepare(MimeMessage) - returns"); //$NON-NLS-1$
                }
            }
        };

        this.mailSender.send(preparator);
    }

    this.mailSender.send(new MimeMessagePreparator() {
        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, EMAIL_ENCODING);
            messageHelper.setSentDate(new Date());
            messageHelper.setText(senderData[1], senderData[0]);
            messageHelper.setSubject(senderData[2]);
            messageHelper.setTo(senderEmail);
            messageHelper.setFrom(getSystemAdminEmail());
        }
    });

    if (log.isDebugEnabled()) {
        log.debug("sendMessage(...) - end");
    }
}

From source file:org.jasig.portlet.blackboardvcportlet.service.impl.MailTemplateServiceImpl.java

public void sendMail(final MailTask mt) {
    try {//from   w w w  .  j a va  2 s.  c o m
        MimeMessagePreparator messagePreparator = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);

                if (mt.getMeetingInvite() != null) {
                    CalendarOutputter outputter = new CalendarOutputter();
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    outputter.setValidating(false);
                    outputter.output(mt.getMeetingInvite(), os);

                    message.addAttachment("invite.ics", new ByteArrayResource(os.toByteArray()));
                }

                message.setFrom(mt.getFrom() != null ? mt.getFrom() : defaultFromAddress);

                if (mt.getTo() != null) {
                    String[] toArray = mt.getTo().toArray(new String[mt.getTo().size()]);
                    message.setTo(toArray);
                }
                if (mt.getSubject() != null) {
                    message.setSubject(mt.getSubject());
                } else {
                    switch (mt.getTemplate()) {
                    case MODERATOR:
                        message.setSubject(moderatorSubject);
                        break;
                    case INTERNAL_PARTICIPANT:
                        message.setSubject(internalParticipantSubject);
                        break;
                    case EXTERNAL_PARTICIPANT:
                        message.setSubject(externalParticipantSubject);
                        break;
                    case SESSION_DELETION:
                        message.setSubject(sessionDeletionSubject);
                        break;
                    default:
                        message.setSubject("");
                    }
                }

                message.setText(buildEmailMessage(mt), false);
            }
        };
        mailSender.send(messagePreparator);
    } catch (Exception e) {
        logger.error("Issue with sending 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 w w  w .  ja  va  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:gov.opm.scrd.batchprocessing.jobs.BatchProcessingJob.java

/**
 * Sends the notification by email./* w w w  .  j ava 2  s.  c om*/
 * <p/>
 * This method does not throw any exception.
 *
 * @param mailMessage The message of the mail.
 * @param mailSubject The subject of the email.
 * @param processType The name of the current processor. It is used to distinguish the recipient of the email.
 */
private void notifyByEmail(String mailMessage, String mailSubject, String processType) {
    mailMessage = mailMessage.replace("@#$%EndingTime%$#@",
            DateFormat.getTimeInstance(DateFormat.LONG, Locale.US).format(new Date()));

    String recipient = processType.equals("BillProcessing") ? billMailRecipient : generalMailRecipient;

    logger.info(
            "Send email to " + recipient + ", subject = [" + mailSubject + "]. Message:" + CRLF + mailMessage);

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

    try {
        helper.setTo(recipient);

        helper.setSubject(mailSubject);

        helper.setText(mailMessage);

        mailSender.send(message);
    } catch (MessagingException e) {
        logger.error("Error sending email to " + recipient + ", subject = [" + mailSubject + "].", e);
    } catch (MailSendException e) {
        logger.error("Error sending email to " + recipient + ", subject = [" + mailSubject + "].", e);
    }
}

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  . ja  v  a 2  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:au.org.theark.core.service.ArkCommonServiceImpl.java

public void sendEmail(final SimpleMailMessage simpleMailMessage) throws MailSendException, VelocityException {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo(simpleMailMessage.getTo());

            // The "from" field is required
            if (simpleMailMessage.getFrom() == null) {
                simpleMailMessage.setFrom(Constants.ARK_ADMIN_EMAIL);
            }//  w  ww. j av a 2  s .  co m

            message.setFrom(simpleMailMessage.getFrom());
            message.setSubject(simpleMailMessage.getSubject());

            // Map all the fields for the email template
            Map<String, Object> model = new HashMap<String, Object>();

            // Add the host name into the footer of the email
            String host = InetAddress.getLocalHost().getHostName();

            // Message title
            model.put("title", "Message from The ARK");
            // Message header
            model.put("header", "Message from The ARK");
            // Message subject
            model.put("subject", simpleMailMessage.getSubject());
            // Message text
            model.put("text", simpleMailMessage.getText());
            // Hostname in message footer
            model.put("host", host);

            // TODO: Add inline image(s)??
            // Add inline image header
            // FileSystemResource res = new FileSystemResource(new
            // File("c:/Sample.jpg"));
            // message.addInline("bgHeaderImg", res);

            // Set up the email text
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "au/org/theark/core/velocity/resetPasswordEmail.vm", model);
            message.setText(text, true);
        }
    };

    // send out the email
    javaMailSender.send(preparator);
}

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

/**
 * @param e/*from  w  ww . j  a v  a2s  .  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:nl.strohalm.cyclos.utils.MailHandler.java

private void doSend(final String subject, final InternetAddress replyTo, final InternetAddress to,
        final String body, final boolean isHTML, final boolean throwException) {
    if (to == null || StringUtils.isEmpty(to.getAddress())) {
        return;//from   ww w. ja va2  s  .  c om
    }
    final LocalSettings localSettings = settingsService.getLocalSettings();
    final MailSettings mailSettings = settingsService.getMailSettings();
    final JavaMailSender mailSender = mailSettings.getMailSender();
    final MimeMessage message = mailSender.createMimeMessage();
    final MimeMessageHelper helper = new MimeMessageHelper(message, localSettings.getCharset());

    try {
        helper.setFrom(getSystemAddress());
        if (replyTo != null) {
            helper.setReplyTo(replyTo);
        }
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(body, isHTML);
        mailSender.send(message);
    } catch (final MessagingException e) {
        if (throwException) {
            throw new MailSendingException(subject, e);
        }
        // Store the current Exception
        CurrentTransactionData.setMailError(new MailSendingException(subject, e));
    } catch (final MailException e) {
        if (throwException) {
            throw new MailSendingException(subject, e);
        }
        CurrentTransactionData.setMailError(new MailSendingException(subject, e));
    }
}

From source file:ome.services.mail.MailUtil.java

/**
 * Main method which takes typical email fields as arguments, to prepare and
 * populate the given new MimeMessage instance and send.
 *
 * @param from//from   w ww.j a v a  2s .co  m
 *            email address message is sent from
 * @param to
 *            email address message is sent to
 * @param topic
 *            topic of the message
 * @param body
 *            body of the message
 * @param html
 *            flag determines the content type to apply.
 * @param ccrecipients
 *            list of email addresses message is sent as copy to
 * @param bccrecipients
 *            list of email addresses message is sent as blind copy to
 */
public void sendEmail(final String from, final String to, final String topic, final String body,
        final boolean html, final List<String> ccrecipients, final List<String> bccrecipients) {

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {

            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setText(body, html);
            message.setFrom(from);
            message.setSubject(topic);
            message.setTo(to);
            if (ccrecipients != null && !ccrecipients.isEmpty()) {
                message.setCc(ccrecipients.toArray(new String[ccrecipients.size()]));
            }

            if (bccrecipients != null && !bccrecipients.isEmpty()) {
                message.setCc(bccrecipients.toArray(new String[bccrecipients.size()]));
            }
        }

    };

    this.mailSender.send(preparator);
}