Search in sources :

Example 1 with MimeMessagePreparator

use of org.springframework.mail.javamail.MimeMessagePreparator in project alf.io by alfio-event.

the class SmtpMailer method send.

@Override
public void send(Event event, String to, List<String> cc, String subject, String text, Optional<String> html, Attachment... attachments) {
    MimeMessagePreparator preparator = (mimeMessage) -> {
        MimeMessageHelper message = html.isPresent() || !ArrayUtils.isEmpty(attachments) ? new MimeMessageHelper(mimeMessage, true, "UTF-8") : new MimeMessageHelper(mimeMessage, "UTF-8");
        message.setSubject(subject);
        message.setFrom(configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), SMTP_FROM_EMAIL)), event.getDisplayName());
        String replyTo = configurationManager.getStringConfigValue(Configuration.from(event.getOrganizationId(), event.getId(), MAIL_REPLY_TO), "");
        if (StringUtils.isNotBlank(replyTo)) {
            message.setReplyTo(replyTo);
        }
        message.setTo(to);
        if (cc != null && !cc.isEmpty()) {
            message.setCc(cc.toArray(new String[cc.size()]));
        }
        if (html.isPresent()) {
            message.setText(text, html.get());
        } else {
            message.setText(text, false);
        }
        if (attachments != null) {
            for (Attachment a : attachments) {
                message.addAttachment(a.getFilename(), new ByteArrayResource(a.getSource()), a.getContentType());
            }
        }
        message.getMimeMessage().saveChanges();
        message.getMimeMessage().removeHeader("Message-ID");
    };
    toMailSender(event).send(preparator);
}
Also used : MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper) MailParseException(org.springframework.mail.MailParseException) MessagingException(javax.mail.MessagingException) ArrayUtils(org.apache.commons.lang3.ArrayUtils) StringUtils(org.apache.commons.lang3.StringUtils) ByteArrayResource(org.springframework.core.io.ByteArrayResource) PropertiesLoaderUtils(org.springframework.core.io.support.PropertiesLoaderUtils) EncodedResource(org.springframework.core.io.support.EncodedResource) Properties(java.util.Properties) JavaMailSender(org.springframework.mail.javamail.JavaMailSender) IOException(java.io.IOException) MimeMessage(javax.mail.internet.MimeMessage) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) MimeMessagePreparator(org.springframework.mail.javamail.MimeMessagePreparator) JavaMailSenderImpl(org.springframework.mail.javamail.JavaMailSenderImpl) Configuration(alfio.model.system.Configuration) Log4j2(lombok.extern.log4j.Log4j2) FileTypeMap(javax.activation.FileTypeMap) Session(javax.mail.Session) Optional(java.util.Optional) Event(alfio.model.Event) AllArgsConstructor(lombok.AllArgsConstructor) MailException(org.springframework.mail.MailException) ConfigurationKeys(alfio.model.system.ConfigurationKeys) InputStream(java.io.InputStream) MimeMessagePreparator(org.springframework.mail.javamail.MimeMessagePreparator) ByteArrayResource(org.springframework.core.io.ByteArrayResource) MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper)

Example 2 with MimeMessagePreparator

use of org.springframework.mail.javamail.MimeMessagePreparator in project kylo by Teradata.

the class SlaEmailService method sendMail.

/**
 * Send an email
 *
 * @param to      the user(s) to send the email to
 * @param subject the subject of the email
 * @param body    the email body
 */
public void sendMail(String to, String subject, String body) {
    try {
        if (testConnection()) {
            MimeMessagePreparator mimeMessagePreparator = new MimeMessagePreparator() {

                @SuppressWarnings({ "rawtypes", "unchecked" })
                public void prepare(MimeMessage message) throws Exception {
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
                    String fromAddress = StringUtils.defaultIfBlank(emailConfiguration.getFrom(), emailConfiguration.getUsername());
                    // message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
                    helper.setFrom(new InternetAddress(fromAddress));
                    helper.setTo(InternetAddress.parse(to));
                    helper.setSubject(subject);
                    helper.setText(body, true);
                // helper.addInline("kylo-logo",new ClassPathResource("kylo-logo-orange-200.png"));
                }
            };
            mailSender.send(mimeMessagePreparator);
            log.debug("Email send to {}", to);
        }
    } catch (MessagingException ex) {
        log.error("Exception while sending mail : {}", ex.getMessage());
        Throwables.propagate(ex);
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMessagePreparator(org.springframework.mail.javamail.MimeMessagePreparator) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper)

Example 3 with MimeMessagePreparator

use of org.springframework.mail.javamail.MimeMessagePreparator in project acs-community-packaging by Alfresco.

the class TemplateMailHelperBean method notifyUser.

/**
 * Send an email notification to the specified User authority
 *
 * @param person     Person node representing the user
 * @param node       Node they are invited too
 * @param from       From text message
 * @param roleText   The role display label for the user invite notification
 */
public void notifyUser(NodeRef person, NodeRef node, final String from, String roleText) {
    final String to = (String) this.getNodeService().getProperty(person, ContentModel.PROP_EMAIL);
    if (to != null && to.length() != 0) {
        String body = this.body;
        if (this.usingTemplate != null) {
            FacesContext fc = FacesContext.getCurrentInstance();
            // use template service to format the email
            NodeRef templateRef = new NodeRef(Repository.getStoreRef(), this.usingTemplate);
            ServiceRegistry services = Repository.getServiceRegistry(fc);
            Map<String, Object> model = DefaultModelHelper.buildDefaultModel(services, Application.getCurrentUser(fc), templateRef);
            model.put("role", roleText);
            model.put("space", node);
            // object to allow client urls to be generated in emails
            model.put("url", new BaseTemplateContentServlet.URLHelper(fc));
            model.put("msg", new I18NMessageMethod());
            model.put("document", node);
            if (nodeService.getType(node).equals(ContentModel.TYPE_CONTENT)) {
                NodeRef parentNodeRef = nodeService.getParentAssocs(node).get(0).getParentRef();
                if (parentNodeRef == null) {
                    throw new IllegalArgumentException("Parent folder doesn't exists for node: " + node);
                }
                model.put("space", parentNodeRef);
            }
            model.put("shareUrl", UrlUtil.getShareUrl(services.getSysAdminParams()));
            body = services.getTemplateService().processTemplate("freemarker", templateRef.toString(), model);
        }
        this.finalBody = body;
        MimeMessagePreparator mailPreparer = new MimeMessagePreparator() {

            public void prepare(MimeMessage mimeMessage) throws MessagingException {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                message.setTo(to);
                message.setSubject(subject);
                message.setText(finalBody, MailActionExecuter.isHTML(finalBody));
                message.setFrom(from);
            }
        };
        if (logger.isDebugEnabled())
            logger.debug("Sending notification email to: " + to + "\n...with subject:\n" + subject + "\n...with body:\n" + body);
        try {
            // Send the message
            this.getMailSender().send(mailPreparer);
        } catch (Throwable e) {
            // don't stop the action but let admins know email is not getting sent
            logger.error("Failed to send email to " + to, e);
        }
    }
}
Also used : FacesContext(javax.faces.context.FacesContext) MimeMessagePreparator(org.springframework.mail.javamail.MimeMessagePreparator) I18NMessageMethod(org.alfresco.repo.template.I18NMessageMethod) BaseTemplateContentServlet(org.alfresco.web.app.servlet.BaseTemplateContentServlet) MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper) NodeRef(org.alfresco.service.cmr.repository.NodeRef) MimeMessage(javax.mail.internet.MimeMessage) ServiceRegistry(org.alfresco.service.ServiceRegistry)

Example 4 with MimeMessagePreparator

use of org.springframework.mail.javamail.MimeMessagePreparator in project BroadleafCommerce by BroadleafCommerce.

the class MessageCreator method buildMimeMessagePreparator.

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

        @Override
        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;
}
Also used : MimeMessagePreparator(org.springframework.mail.javamail.MimeMessagePreparator) MimeMessage(javax.mail.internet.MimeMessage) EmailTarget(org.broadleafcommerce.common.email.domain.EmailTarget) EmailInfo(org.broadleafcommerce.common.email.service.info.EmailInfo) MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Example 5 with MimeMessagePreparator

use of org.springframework.mail.javamail.MimeMessagePreparator in project BroadleafCommerce by BroadleafCommerce.

the class MessageCreator method sendMessage.

public void sendMessage(final Map<String, Object> props) throws MailException {
    MimeMessagePreparator preparator = buildMimeMessagePreparator(props);
    this.mailSender.send(preparator);
}
Also used : MimeMessagePreparator(org.springframework.mail.javamail.MimeMessagePreparator)

Aggregations

MimeMessagePreparator (org.springframework.mail.javamail.MimeMessagePreparator)13 MimeMessageHelper (org.springframework.mail.javamail.MimeMessageHelper)10 MimeMessage (javax.mail.internet.MimeMessage)7 JavaMailSender (org.springframework.mail.javamail.JavaMailSender)5 Autowired (org.springframework.beans.factory.annotation.Autowired)4 HashMap (java.util.HashMap)3 List (java.util.List)3 Map (java.util.Map)3 Logger (org.slf4j.Logger)3 LoggerFactory (org.slf4j.LoggerFactory)3 Value (org.springframework.beans.factory.annotation.Value)3 MailException (org.springframework.mail.MailException)3 Service (org.springframework.stereotype.Service)3 Configuration (freemarker.template.Configuration)2 Template (freemarker.template.Template)2 InputStreamReader (java.io.InputStreamReader)2 MessagingException (javax.mail.MessagingException)2 FreeMarkerTemplateUtils (org.springframework.ui.freemarker.FreeMarkerTemplateUtils)2 Event (alfio.model.Event)1 Configuration (alfio.model.system.Configuration)1