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

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

Introduction

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

Prototype

public void setFrom(String from) throws MessagingException 

Source Link

Usage

From source file:com.campodejazayeri.wedding.AdminController.java

private void sendEmail(String to, String subject, String body) throws Exception {
    MimeMessage msg = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(msg, "UTF-8");
    helper.setFrom("Darius and Monica <campodejazayeri@gmail.com>");
    helper.setTo(to);/*from www .ja va  2s .c  o  m*/
    helper.setSubject(subject);
    helper.setText(body);
    mailSender.send(msg);
}

From source file:com.cfitzarl.cfjwed.service.impl.EmailDispatchingServiceImpl.java

/** {@inheritDoc} **/
@Override//  w  ww.  j a va 2  s.c o m
public void send(String to, String subject, String template, Map<String, Object> attrs) {
    // Add message source decorator to attributes list for localization
    attrs.put("localeSource", localizationService);

    String htmlFilename = String.format("/email-templates/%s-html.vm", template);
    String textFilename = String.format("/email-templates/%s-text.vm", template);

    String htmlContent = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, htmlFilename, "UTF-8",
            attrs);
    String textContent = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, textFilename, "UTF-8",
            attrs);

    try {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        String fromEmail = configDao.findByKey(ConfigKey.EMAIL).getValue();
        String fromTitle = configDao.findByKey(ConfigKey.TITLE).getValue();

        String from = String.format("%s <%s>", fromTitle, fromEmail);

        helper.setTo(to);
        helper.setSubject(subject);
        helper.setFrom(from);
        helper.setReplyTo(from);
        helper.setText(textContent, htmlContent);

        taskExecutor.submit(new MailRunner(message, javaMailSender));
    } catch (MessagingException e) {
        LOGGER.error("Error generating mail message", e);
    }
}

From source file:hornet.framework.mail.MailServiceImpl.java

/**
 * {@inheritDoc}/*w ww  .ja  va  2  s . c o  m*/
 */
@Override
public void envoyer(final String expediteur, final String sujet, final String message,
        final Map<String, Object> paramMap, final String... destinataires) {

    try {
        final Session session = ((JavaMailSenderImpl) mailSender).getSession();
        HornetMimeMessage mMessage = null;
        if (messageIdDomainName == null || messageIdDomainName.length() == 0) {
            mMessage = new HornetMimeMessage(nomApplication, session);
        } else {
            mMessage = new HornetMimeMessage(nomApplication, messageIdDomainName, session);
        }

        mMessage.setHeader("Content-Type", "text/html");
        final MimeMessageHelper helper = new MimeMessageHelper(mMessage, true, CharEncoding.UTF_8);

        addExtraSmtpField(paramMap, helper);

        helper.setFrom(expediteur);

        ajouterDestinataires(helper, destinataires);

        helper.setSubject(sujet);
        // message aux formats texte et html
        helper.setText(preparerMessageTexte(message), preparerMessageHTML(message));

        mailSender.send(mMessage);
    } catch (final MailSendException mse) {
        throw toBusinessException(mse);
    } catch (final Exception e) {
        throw new BusinessException("erreur.envoi.courriel", e);
    }
}

From source file:com.campodejazayeri.wedding.AdminController.java

@RequestMapping("/testmail")
@ResponseBody/*from   w  w  w.  j  a v  a  2  s .c  o m*/
public String testMail() throws Exception {
    MimeMessage message = mailSender.createMimeMessage();
    //SimpleMailMessage msg = new SimpleMailMessage();
    MimeMessageHelper msg = new MimeMessageHelper(message, "UTF-8");
    msg.setFrom("Darius and Monica <campodejazayeri@gmail.com>");
    msg.setTo("djazayeri@gmail.com");
    msg.setSubject("Testing wedding mail");
    msg.setText("Monica Campo Patio sabe escribir con .");
    mailSender.send(message);
    return "Sent!";
}

From source file:com.glaf.mail.MailSenderImpl.java

public void send(JavaMailSender javaMailSender, MailMessage mailMessage) throws Exception {
    if (StringUtils.isEmpty(mailMessage.getMessageId())) {
        mailMessage.setMessageId(UUID32.getUUID());
    }/*from w  w  w . j  av  a  2 s . co  m*/

    mailHelper = new MxMailHelper();
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();

    MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

    if (StringUtils.isNotEmpty(mailMessage.getFrom())) {
        messageHelper.setFrom(mailMessage.getFrom());
        mailFrom = mailMessage.getFrom();
    } else {
        if (StringUtils.isEmpty(mailFrom)) {
            mailFrom = MailProperties.getString("mail.mailFrom");
        }
        messageHelper.setFrom(mailFrom);
    }

    logger.debug("mailFrom:" + mailFrom);

    if (mailMessage.getTo() != null) {
        messageHelper.setTo(mailMessage.getTo());
    }

    if (mailMessage.getCc() != null) {
        messageHelper.setCc(mailMessage.getCc());
    }

    if (mailMessage.getBcc() != null) {
        messageHelper.setBcc(mailMessage.getBcc());
    }

    if (mailMessage.getReplyTo() != null) {
        messageHelper.setReplyTo(mailMessage.getReplyTo());
    }

    String mailSubject = mailMessage.getSubject();
    if (mailSubject == null) {
        mailSubject = "";
    }

    if (mailSubject != null) {
        // mailSubject = MimeUtility.encodeText(new
        // String(mailSubject.getBytes(), encoding), encoding, "B");
        mailSubject = MimeUtility.encodeWord(mailSubject);
    }

    mimeMessage.setSubject(mailSubject);

    Map<String, Object> dataMap = mailMessage.getDataMap();
    if (dataMap == null) {
        dataMap = new java.util.HashMap<String, Object>();
    }

    String serviceUrl = SystemConfig.getServiceUrl();

    logger.debug("mailSubject:" + mailSubject);
    logger.debug("serviceUrl:" + serviceUrl);

    if (serviceUrl != null) {
        String loginUrl = serviceUrl + "/mx/login";
        String mainUrl = serviceUrl + "/mx/main";
        logger.debug("loginUrl:" + loginUrl);
        dataMap.put("loginUrl", loginUrl);
        dataMap.put("mainUrl", mainUrl);
    }

    mailMessage.setDataMap(dataMap);

    if (StringUtils.isEmpty(mailMessage.getContent())) {
        Template template = TemplateContainer.getContainer().getTemplate(mailMessage.getTemplateId());
        if (template != null) {
            String templateType = template.getTemplateType();
            logger.debug("templateType:" + templateType);
            // logger.debug("content:" + template.getContent());
            if (StringUtils.equals(templateType, "eml")) {
                if (template.getContent() != null) {
                    Mail m = mailHelper.getMail(template.getContent().getBytes());
                    String content = m.getContent();
                    if (StringUtils.isNotEmpty(content)) {
                        template.setContent(content);
                        try {
                            Writer writer = new StringWriter();
                            TemplateUtils.evaluate(mailMessage.getTemplateId(), dataMap, writer);
                            String text = writer.toString();
                            writer.close();
                            writer = null;
                            mailMessage.setContent(text);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            throw new RuntimeException(ex);
                        }
                    }
                }
            } else {
                try {
                    String text = TemplateUtils.process(dataMap, template.getContent());
                    mailMessage.setContent(text);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    if (StringUtils.isNotEmpty(mailMessage.getContent())) {
        String text = mailMessage.getContent();
        if (StringUtils.isNotEmpty(callbackUrl)) {
            String href = callbackUrl + "?messageId=" + mailMessage.getMessageId();
            text = mailHelper.embedCallbackScript(text, href);
            mailMessage.setContent(text);
            logger.debug(text);
            messageHelper.setText(text, true);
        }
        messageHelper.setText(text, true);
    }

    logger.debug("mail body:" + mailMessage.getContent());

    Collection<Object> files = mailMessage.getFiles();

    if (files != null && !files.isEmpty()) {
        Iterator<Object> iterator = files.iterator();
        while (iterator.hasNext()) {
            Object object = iterator.next();
            if (object instanceof java.io.File) {
                java.io.File file = (java.io.File) object;
                FileSystemResource resource = new FileSystemResource(file);
                String name = file.getName();
                name = MailTools.chineseStringToAscii(name);
                messageHelper.addAttachment(name, resource);
                logger.debug("add attachment:" + name);
            } else if (object instanceof DataSource) {
                DataSource dataSource = (DataSource) object;
                String name = dataSource.getName();
                name = MailTools.chineseStringToAscii(name);
                messageHelper.addAttachment(name, dataSource);
                logger.debug("add attachment:" + name);
            } else if (object instanceof DataFile) {
                DataFile dataFile = (DataFile) object;
                if (StringUtils.isNotEmpty(dataFile.getFilename())) {
                    String name = dataFile.getFilename();
                    name = MailTools.chineseStringToAscii(name);
                    InputStreamSource inputStreamSource = new MxMailInputSource(dataFile);
                    messageHelper.addAttachment(name, inputStreamSource);
                    logger.debug("add attachment:" + name);
                }
            }
        }
    }

    mimeMessage.setSentDate(new java.util.Date());

    javaMailSender.send(mimeMessage);

    logger.info("-----------------------------------------");
    logger.info("????");
    logger.info("-----------------------------------------");
}

From source file:info.jtrac.mail.MailSender.java

public void send(Item item) {
    if (sender == null) {
        logger.debug("mail sender is null, not sending notifications");
        return;/*from  ww w.j  av a  2s  . c o  m*/
    }
    // TODO make this locale sensitive per recipient        
    logger.debug("attempting to send mail for item update");
    // prepare message content
    StringBuffer sb = new StringBuffer();
    String anchor = getItemViewAnchor(item, defaultLocale);
    sb.append(anchor);
    sb.append(ItemUtils.getAsHtml(item, messageSource, defaultLocale));
    sb.append(anchor);
    if (logger.isDebugEnabled()) {
        logger.debug("html content: " + sb);
    }
    // prepare message
    MimeMessage message = sender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");
    try {
        helper.setText(addHeaderAndFooter(sb), true);
        helper.setSubject(getSubject(item));
        helper.setSentDate(new Date());
        helper.setFrom(from);
        // set TO            
        if (item.getAssignedTo() != null) {
            helper.setTo(item.getAssignedTo().getEmail());
        } else {
            helper.setTo(item.getLoggedBy().getEmail());
        }
        // set CC
        if (item.getItemUsers() != null) {
            String[] cc = new String[item.getItemUsers().size()];
            int i = 0;
            for (ItemUser itemUser : item.getItemUsers()) {
                cc[i++] = itemUser.getUser().getEmail();
            }
            helper.setCc(cc);
        }
        // send message
        sendInNewThread(message);
    } catch (Exception e) {
        logger.error("failed to prepare e-mail", e);
    }
}

From source file:org.toobsframework.email.SmtpMailSender.java

public void sendEmail(EmailBean email) throws MailException, MessagingException {
    JavaMailSender javaMailSender = (JavaMailSender) javaMailSenders.get(email.getMailSenderKey());
    if (javaMailSender == null) {
        throw new MessagingException(email.getMailSenderKey() + " is an invalid mailSenderKey");
    }/*from   w ww.jav  a 2s .  c  o  m*/
    if (this.getMailProperties() != null) {
        ((JavaMailSenderImpl) javaMailSender).setJavaMailProperties(this.getMailProperties());
    }
    try {
        String[] recipients = this.processRecipients(email.getRecipients());
        String[] bccs = new String[email.getBccs().size()];
        for (int i = 0; i < recipients.length; i++) {
            MimeMessage message = null;
            MimeMessageHelper helper = null;
            String thisRecipient = recipients[i];
            switch (email.getType()) {
            case EmailBean.MESSAGE_TYPE_TEXT:
                message = javaMailSender.createMimeMessage();
                helper = new MimeMessageHelper(message, false, "us-ascii");
                helper.setSubject(email.getEmailSubject());
                helper.setFrom(email.getEmailSender());

                helper.setTo(thisRecipient);
                helper.setBcc((String[]) email.getBccs().toArray(bccs));
                helper.setText(email.getMessageText(), false);
                log.info("Sending message " + message.toString());
                javaMailSender.send(message);
                break;
            case EmailBean.MESSAGE_TYPE_HTML:
                message = javaMailSender.createMimeMessage();
                helper = new MimeMessageHelper(message, true, "us-ascii");
                helper.setSubject(email.getEmailSubject());
                helper.setFrom(email.getEmailSender());

                helper.setTo(thisRecipient);
                helper.setBcc((String[]) email.getBccs().toArray(bccs));
                helper.setText(email.getMessageText(), email.getMessageHtml());
                log.info("Sending message " + message.toString());
                javaMailSender.send(message);
                break;
            }
        }
    } catch (Exception e) {
        log.error("Mail exception " + e.getMessage(), e);
        throw new MessagingException(e.getMessage());
    }
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java

public void sendMailNotification(ReportExecutionJob job, ReportJob jobDetails, List reportOutputs)
        throws JobExecutionException {
    ReportJobMailNotification mailNotification = jobDetails.getMailNotification();

    if (mailNotification != null) {
        try {/*from w  w w  .  j  av  a 2 s .c  o m*/
            // skip mail notification when job fails
            if (mailNotification.isSkipNotificationWhenJobFails() && (!job.exceptions.isEmpty())) {
                return;
            }
            JavaMailSender mailSender = job.getMailSender();
            String fromAddress = job.getFromAddress();
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, job.getCharacterEncoding());
            messageHelper.setFrom(fromAddress);
            messageHelper.setSubject(mailNotification.getSubject());

            StringBuffer messageText = new StringBuffer();
            addMailRecipients(mailNotification, messageHelper);

            boolean isEmailBodyOccupied = false;

            if (reportOutputs != null && !reportOutputs.isEmpty()) {
                byte resultSendType = jobDetails.getMailNotification().getResultSendType();

                if ((resultSendType == ReportJobMailNotification.RESULT_SEND_EMBED)
                        || (resultSendType == ReportJobMailNotification.RESULT_SEND_EMBED_ZIP_ALL_OTHERS)) {
                    List attachmentReportList = new ArrayList();
                    for (Iterator it = reportOutputs.iterator(); it.hasNext();) {
                        ReportOutput output = (ReportOutput) it.next();
                        if ((!isEmailBodyOccupied) && output.getFileType().equals(ContentResource.TYPE_HTML)
                                && (job.exceptions.isEmpty())) {
                            // only embed html output
                            embedOutput(messageHelper, output);
                            isEmailBodyOccupied = true;
                        } else if (resultSendType == ReportJobMailNotification.RESULT_SEND_EMBED) {
                            // save the rest of the output as attachments
                            attachOutput(job, messageHelper, output,
                                    (resultSendType == ReportJobMailNotification.RESULT_SEND_ATTACHMENT));
                        } else { // RESULT_SEND_EMBED_ZIP_ALL_OTHERS
                            attachmentReportList.add(output);
                        }
                    }
                    if (attachmentReportList.size() > 0) {
                        // put the rest of attachments in 1 zip file
                        attachOutputs(job, messageHelper, attachmentReportList);

                    }
                } else if (resultSendType == ReportJobMailNotification.RESULT_SEND_ATTACHMENT
                        || resultSendType == ReportJobMailNotification.RESULT_SEND_ATTACHMENT_NOZIP) {
                    for (Iterator it = reportOutputs.iterator(); it.hasNext();) {
                        ReportOutput output = (ReportOutput) it.next();
                        attachOutput(job, messageHelper, output,
                                (resultSendType == ReportJobMailNotification.RESULT_SEND_ATTACHMENT));
                    }
                } else if (resultSendType == ReportJobMailNotification.RESULT_SEND_ATTACHMENT_ZIP_ALL) {
                    // put all the attachments in 1 zip file
                    attachOutputs(job, messageHelper, reportOutputs);
                } else {
                    appendRepositoryLinks(job, messageText, reportOutputs);
                }
            }
            if (mailNotification.isIncludingStackTraceWhenJobFails()) {
                if (!job.exceptions.isEmpty()) {
                    for (Iterator it = job.exceptions.iterator(); it.hasNext();) {
                        ExceptionInfo exception = (ExceptionInfo) it.next();

                        messageText.append("\n");
                        messageText.append(exception.getMessage());

                        attachException(messageHelper, exception);
                    }
                }
            }
            String text = mailNotification.getMessageText();
            if (!job.exceptions.isEmpty()) {
                if (mailNotification.getMessageTextWhenJobFails() != null)
                    text = mailNotification.getMessageTextWhenJobFails();
                else
                    text = job.getMessage("report.scheduling.job.default.mail.notification.message.on.fail",
                            null);
            }
            if (!isEmailBodyOccupied)
                messageHelper.setText(text + "\n" + messageText.toString());
            mailSender.send(message);
        } catch (MessagingException e) {
            log.error("Error while sending report job result mail", e);
            throw new JSExceptionWrapper(e);
        }
    }
}

From source file:de.thm.arsnova.services.UserService.java

private void sendEmail(DbUser dbUser, String subject, String body) {
    MimeMessage msg = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(msg, "UTF-8");
    try {//www .ja  v  a 2 s.  com
        helper.setFrom(mailSenderName + "<" + mailSenderAddress + ">");
        helper.setTo(dbUser.getUsername());
        helper.setSubject(subject);
        helper.setText(body);

        LOGGER.info("Sending mail \"{}\" from \"{}\" to \"{}\"",
                new Object[] { subject, msg.getFrom(), dbUser.getUsername() });
        mailSender.send(msg);
    } catch (MessagingException e) {
        LOGGER.warn("Mail \"{}\" could not be sent: {}", subject, e);
    } catch (MailException e) {
        LOGGER.warn("Mail \"{}\" could not be sent: {}", subject, e);
    }
}

From source file:cdr.forms.EmailNotificationHandler.java

private void sendNotice(HashMap<String, Object> model, Form form, List<String> recipients) {

    if (recipients == null || recipients.isEmpty())
        return;/*from   w ww  . ja v  a2 s .c  om*/

    StringWriter htmlsw = new StringWriter();
    StringWriter textsw = new StringWriter();

    try {
        depositNoticeHtmlTemplate.process(model, htmlsw);
        depositNoticeTextTemplate.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);
        for (String recipient : recipients) {
            message.addTo(recipient);
        }
        message.setSubject("Deposit to " + form.getTitle() + " by " + form.getCurrentUser());
        message.setFrom(this.getFromAddress());
        message.setText(textsw.toString(), htmlsw.toString());
        this.mailSender.send(mimeMessage);
    } catch (MessagingException e) {
        LOG.error("problem sending deposit message", e);
        return;
    }
}