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) 

Source Link

Document

Create a new MimeMessageHelper for the given MimeMessage, assuming a simple text message (no multipart content, i.e.

Usage

From source file:com.apress.progwt.server.service.impl.InvitationServiceImpl.java

public void sendInvite(final MailingListEntry invitation) throws InfrastructureException {
    // send mail//from w  ww.  ja  va2s . c o  m
    try {
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                message.setTo(invitation.getEmail());
                message.setFrom(from);
                message.setSubject("ToCollege.net Invitation");

                Map<String, Object> model = new HashMap<String, Object>();
                model.put("inviter", invitation.getInviter());
                model.put("randomkey", invitation.getRandomkey());
                model.put("email", invitation.getEmail());

                Template textTemplate = configurer.getConfiguration().getTemplate(invitationTemplate);
                final StringWriter textWriter = new StringWriter();

                textTemplate.process(model, textWriter);

                message.setText(textWriter.toString(), true);

                log.info("Inviting: " + invitation.getEmail());
                log.debug("From: " + from);
                log.debug("Message: " + textWriter.toString());

            }
        };
        this.mailSender.send(preparator);

        invitation.setSentEmailOk(true);
        mailingListDAO.save(invitation);

    } catch (Exception e) {
        log.error(e);
        throw new InfrastructureException(e);
    }
}

From source file:csns.util.EmailUtils.java

public boolean sendHtmlMail(Email email) {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message);

    try {//from  w  w  w .  j a  v  a 2s  .c o m
        message.setContent(getHtml(email), "text/html");

        helper.setSubject(email.getSubject());
        helper.setFrom(email.getAuthor().getPrimaryEmail());
        helper.setCc(email.getAuthor().getPrimaryEmail());
        String addresses[] = getAddresses(email.getRecipients(), email.isUseSecondaryEmail())
                .toArray(new String[0]);
        if (addresses.length > 1) {
            helper.setTo(appEmail);
            helper.setBcc(addresses);
        } else
            helper.setTo(addresses);

        mailSender.send(message);

        logger.info(email.getAuthor().getUsername() + " sent email to "
                + StringUtils.arrayToCommaDelimitedString(addresses));

        return true;
    } catch (MessagingException e) {
        logger.warn("Fail to send MIME message", e);
    }

    return false;
}

From source file:com.cerebro.provevaadin.smtp.ConfigurazioneSMTPSpring.java

public ConfigurazioneSMTPSpring() {

    TextField smtpHost = new TextField("SMTP Host Server");
    smtpHost.setRequired(true);/*w w w . ja  va2s  .  c  o  m*/
    TextField smtpPort = new TextField("SMTP Port");
    smtpPort.setRequired(true);
    TextField smtpUser = new TextField("SMTP Username");
    smtpUser.setRequired(true);
    PasswordField smtpPwd = new PasswordField("SMTP Password");
    smtpPwd.setRequired(true);
    PasswordField pwdConf = new PasswordField("Conferma la Password");
    pwdConf.setRequired(true);
    CheckBox security = new CheckBox("Sicurezza del server");

    Properties props = new Properties();
    InputStream config = VaadinServlet.getCurrent().getServletContext()
            .getResourceAsStream("/WEB-INF/config.properties");
    if (config != null) {
        System.out.println("Carico file di configurazione");
        try {
            props.load(config);
        } catch (IOException ex) {
            Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    smtpHost.setValue(props.getProperty("mail.smtp.host"));
    smtpUser.setValue(props.getProperty("smtp_user"));
    security.setValue(Boolean.parseBoolean(props.getProperty("smtp_sec")));

    Button salva = new Button("Salva i parametri");
    salva.addClickListener((Button.ClickEvent event) -> {
        System.out.println("Salvo i parametri SMTP");
        if (smtpHost.isValid() && smtpPort.isValid() && smtpUser.isValid() && smtpPwd.isValid()
                && smtpPwd.getValue().equals(pwdConf.getValue())) {
            System.out.println(smtpHost.getValue() + smtpPort.getValue() + smtpUser.getValue()
                    + smtpPwd.getValue() + security.getValue().toString());
            props.setProperty("mail.smtp.host", smtpHost.getValue());
            props.setProperty("mail.smtp.port", smtpPort.getValue());
            props.setProperty("smtp_user", smtpUser.getValue());
            props.setProperty("smtp_pwd", smtpPwd.getValue());
            props.setProperty("mail.smtp.ssl.enable", security.getValue().toString());
            String webInfPath = VaadinServlet.getCurrent().getServletConfig().getServletContext()
                    .getRealPath("WEB-INF");
            File f = new File(webInfPath + "/config.properties");
            try {
                OutputStream o = new FileOutputStream(f);
                try {
                    props.store(o, "Prova");
                } catch (IOException ex) {
                    Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex);
            }
            Notification.show("Parametri salvati");
        } else {
            Notification.show("Ricontrolla i parametri");
        }

    });

    TextField emailTest = new TextField("Destinatario Mail di Prova");
    emailTest.setImmediate(true);
    emailTest.addValidator(new EmailValidator("Mail non valida"));

    Button test = new Button("Invia una mail di prova");
    test.addClickListener((Button.ClickEvent event) -> {
        System.out.println("Invio della mail di prova");
        if (emailTest.isValid() && !emailTest.isEmpty()) {
            System.out.println("Invio mail di prova a " + emailTest.getValue());
            JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
            mailSender.setJavaMailProperties(props);
            mailSender.setUsername(props.getProperty("smtp_user"));
            mailSender.setPassword(props.getProperty("smtp_pwd"));
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            try {
                helper.setFrom("dottmatteocasagrande@gmail.com");
                helper.setSubject("Subject");
                helper.setText("It works!");
                helper.addTo(emailTest.getValue());
                mailSender.send(message);
            } catch (MessagingException ex) {
                Logger.getLogger(ConfigurazioneSMTPSpring.class.getName()).log(Level.SEVERE, null, ex);
            }

        } else {
            Notification.show("Controlla l'indirizzo mail del destinatario");
        }
    });

    this.addComponents(smtpHost, smtpPort, smtpUser, smtpPwd, pwdConf, security, salva, emailTest, test);

}

From source file:business.services.MailService.java

@Transactional
public void notifyScientificCouncil(@NotNull RequestRepresentation request) {
    log.info("Notify scientic council for request " + request.getProcessInstanceId() + ".");

    List<User> members = userService.findScientificCouncilMembers();
    for (User member : members) {
        log.info("Sending notification to user " + member.getUsername());
        try {/*from w ww.ja v  a2  s . c  o  m*/
            MimeMessageHelper message = new MimeMessageHelper(mailSender.createMimeMessage());
            message.setTo(member.getContactData().getEmail());
            message.setFrom(getFrom(), fromName);
            message.setReplyTo(replyAddress, replyName);
            message.setSubject(String.format("Nieuwe PALGA-aanvraag aan u voorgelegd, aanvraagnummer: %s",
                    request.getRequestNumber()));
            String requestLink = getLink("/#/request/view/" + request.getProcessInstanceId());
            message.setText(String.format(scientificCouncilNotificationTemplate, requestLink));
            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:com.globocom.grou.report.ReportService.java

private void notifyByMail(Test test, String email, Map<String, Double> result) throws Exception {
    MimeMessagePreparator messagePreparator = mimeMessage -> {
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setTo(email);//w  w  w  .j  a  v a 2  s  .c  o  m
        messageHelper.setFrom(MAIL_FROM);
        messageHelper.setSubject(getSubject(test));
        Context context = new Context();
        context.setVariable("project", test.getProject());
        context.setVariable("name", test.getName());
        HashMap<String, Object> testContext = new HashMap<>();
        testContext.put("dashboard", test.getDashboard());
        testContext.put("loaders", test.getLoaders().stream().map(Loader::getName).collect(Collectors.toSet()));
        testContext.put("properties", test.getProperties());
        testContext.put("id", test.getId());
        testContext.put("created", test.getCreatedDate().toString());
        testContext.put("lastModified", test.getLastModifiedDate().toString());
        testContext.put("durationTimeMillis", test.getDurationTimeMillis());
        context.setVariable("testContext", mapper.writeValueAsString(testContext).split("\\R"));
        Set<String> tags = test.getTags();
        context.setVariable("tags", tags);
        context.setVariable("metrics", new TreeMap<>(result));
        String content = templateEngine.process("reportEmail", context);
        messageHelper.setText(content, true);
    };
    try {
        emailSender.send(messagePreparator);
        LOGGER.info(
                "Test " + test.getProject() + "." + test.getName() + ": sent notification to email " + email);
    } catch (MailException e) {
        LOGGER.error(e.getMessage(), e);
    }
}

From source file:br.ufc.ivela.commons.mail.MailService.java

public List<MimeMessage> send(String[] to, String from, String subject, String content)
        throws MessagingException {

    if (to == null || to.length <= 0) {
        throw new IllegalArgumentException("You cannot send an email without recipients");
    }/*from w  w w .  j av  a2  s.co m*/

    if (from == null || from.isEmpty()) {
        throw new IllegalArgumentException("You cannot send an email without a sender");
    }

    if (subject == null || subject.isEmpty()) {
        throw new IllegalArgumentException("You cannot send an email without a subject");
    }

    content = content != null ? content : "";

    // Construct the message
    MimeMessage[] messagesToSend = new MimeMessage[to.length];

    for (int i = 0; i < to.length; i++) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        helper.setTo(to[i]);
        helper.setFrom(from);
        helper.setSubject(subject);
        helper.setText(content, true);
        messagesToSend[i] = message;
    }

    List<MimeMessage> messagesNotSent = new ArrayList<MimeMessage>(messagesToSend.length);

    if (disabled)
        return messagesNotSent;

    for (MimeMessage message : messagesToSend) {
        try {
            this.mailSender.send(message);
        } catch (Exception e) {
            log.error("Error sending Email to:" + message.toString(), e);
            messagesNotSent.add(message);
        }
    }

    return messagesNotSent;
}

From source file:br.ufc.ivela.commons.mail.MailService.java

private MimeMessage createMessage(String to, String from, String subject, String velocityTemplate, Map params)
        throws MessagingException {
    MimeMessage mime = mailSender.createMimeMessage();
    MimeMessageHelper message = new MimeMessageHelper(mime);
    message.setTo(to);// w  w  w  . j  a v a2 s . c o  m
    message.setFrom(from);
    message.setSubject(subject);
    String text = velocityTemplate != null && !velocityTemplate.isEmpty()
            ? VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, velocityTemplate, params)
            : "";
    message.setText(text, true);

    return mime;
}

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  w  ww.  j  a va  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:cz.zcu.kiv.eegdatabase.webservices.rest.user.UserServiceImpl.java

/**
 * Method for sending registration confirmation email.
 *
 * @param registrationPath path to registration confirmation page
 * @param plainPassword    password in plain text
 * @param user             created user object
 * @param locale           locale/*from   w  w  w .  j a v a2s .  c o m*/
 * @throws MailException      error during sending mail
 * @throws MessagingException error during sending mail
 */
private void sendRegistrationConfirmMail(String registrationPath, String plainPassword, Person user,
        Locale locale) throws MailException, MessagingException {
    log.debug("Creating email content");
    StringBuilder sb = new StringBuilder();
    String login = "<b>" + user.getUsername() + "</b>";

    sb.append("<html><body>");
    sb.append("<h4>");
    sb.append(messageSource.getMessage("registration.email.welcome", null, locale));
    sb.append("</h4>");
    sb.append("<p>");
    sb.append(messageSource.getMessage("registration.email.body.yourLogin", new String[] { login }, locale));
    sb.append("</p>");
    sb.append("<p>");
    sb.append(messageSource.getMessage("registration.email.body.yourPassword", new String[] { plainPassword },
            locale));
    sb.append("</p>");
    sb.append("<p>");
    sb.append(messageSource.getMessage("registration.email.body.clickToRegister", null, locale));
    sb.append("<br/>");

    String confirmURL = registrationPath + user.getAuthenticationHash();
    sb.append("<a href=\"").append(confirmURL).append("\">").append(confirmURL).append("</a>");
    sb.append("</p>");
    sb.append("</body></html>");

    String emailSubject = messageSource.getMessage("registration.email.subject", null, locale);
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
    message.setFrom(mailMessage.getFrom());
    message.setTo(user.getEmail());
    message.setSubject(emailSubject);
    message.setText(sb.toString(), true);
    mailSender.send(mimeMessage);
}

From source file:org.jresponder.message.MessageRefImpl.java

/**
 * Render a message in the context of a particular subscriber
 * and subscription.//from   w w  w.j  a v a  2  s  .c o m
 */
@Override
public boolean populateMessage(MimeMessage aMimeMessage, SendConfig aSendConfig, Subscriber aSubscriber,
        Subscription aSubscription) {

    try {

        // prepare context
        Map<String, Object> myRenderContext = new HashMap<String, Object>();
        myRenderContext.put("subscriber", aSubscriber);
        myRenderContext.put("subscription", aSubscription);
        myRenderContext.put("config", aSendConfig);
        myRenderContext.put("message", this);

        // render the whole file
        String myRenderedFileContents = TextRenderUtil.getInstance().render(fileContents, myRenderContext);

        // now parse again with Jsoup
        Document myDocument = Jsoup.parse(myRenderedFileContents);

        String myHtmlBody = "";
        String myTextBody = "";

        // html body
        Elements myBodyElements = myDocument.select("#htmlbody");
        if (!myBodyElements.isEmpty()) {
            myHtmlBody = myBodyElements.html();
        }

        // text body
        Elements myJrTextBodyElements = myDocument.select("#textbody");
        if (!myJrTextBodyElements.isEmpty()) {
            myTextBody = TextUtil.getInstance().getWholeText(myJrTextBodyElements.first());
        }

        // now build the actual message
        MimeMessage myMimeMessage = aMimeMessage;
        // wrap it in a MimeMessageHelper - since some things are easier with that
        MimeMessageHelper myMimeMessageHelper = new MimeMessageHelper(myMimeMessage);

        // set headers

        // subject
        myMimeMessageHelper.setSubject(TextRenderUtil.getInstance()
                .render((String) propMap.get(MessageRefProp.JR_SUBJECT.toString()), myRenderContext));

        // TODO: implement DKIM, figure out subetha

        String mySenderEmailPattern = aSendConfig.getSenderEmailPattern();
        String mySenderEmail = TextRenderUtil.getInstance().render(mySenderEmailPattern, myRenderContext);
        myMimeMessage.setSender(new InternetAddress(mySenderEmail));

        myMimeMessageHelper.setTo(aSubscriber.getEmail());

        // from
        myMimeMessageHelper.setFrom(
                TextRenderUtil.getInstance()
                        .render((String) propMap.get(MessageRefProp.JR_FROM_EMAIL.toString()), myRenderContext),
                TextRenderUtil.getInstance()
                        .render((String) propMap.get(MessageRefProp.JR_FROM_NAME.toString()), myRenderContext));

        // see how to set body

        // if we have both text and html, then do multipart
        if (myTextBody.trim().length() > 0 && myHtmlBody.trim().length() > 0) {

            // create wrapper multipart/alternative part
            MimeMultipart ma = new MimeMultipart("alternative");
            myMimeMessage.setContent(ma);
            // create the plain text
            BodyPart plainText = new MimeBodyPart();
            plainText.setText(myTextBody);
            ma.addBodyPart(plainText);
            // create the html part
            BodyPart html = new MimeBodyPart();
            html.setContent(myHtmlBody, "text/html");
            ma.addBodyPart(html);
        }

        // if only HTML, then just use that
        else if (myHtmlBody.trim().length() > 0) {
            myMimeMessageHelper.setText(myHtmlBody, true);
        }

        // if only text, then just use that
        else if (myTextBody.trim().length() > 0) {
            myMimeMessageHelper.setText(myTextBody, false);
        }

        // if neither text nor HTML, then the message is being skipped,
        // so we just return null
        else {
            return false;
        }

        return true;

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

}