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:dk.teachus.backend.bean.impl.SpringMailBean.java

public void sendMail(final InternetAddress sender, final InternetAddress recipient, final String subject,
        final String body, final Type mailType) throws MailException {
    try {//ww w.j  a  v  a 2 s . c om
        mailSender.send(new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false, "UTF-8");

                message.setFrom(sender);
                message.addTo(recipient);
                message.setSubject(subject);

                switch (mailType) {
                case HTML:
                    message.setText(body, true);
                    break;
                default:
                    message.setText(body);
                    break;
                }
            }
        });
    } catch (MailSendException e) {
        Map<?, ?> failedMessages = e.getFailedMessages();

        if (failedMessages != null && failedMessages.isEmpty() == false) {
            Object object = failedMessages.values().iterator().next();
            if (object != null) {
                Exception mailException = (Exception) object;
                if (mailException.getCause() instanceof SMTPAddressFailedException) {
                    throw new RecipientErrorMailException(e);
                }
            }
        }

        throw new MailException(e);
    }
}

From source file:com.foilen.smalltools.email.EmailServiceSpring.java

@Override
public void sendEmail(EmailBuilder emailBuilder) {

    try {//from  www  .j a  v a 2s. c  o m
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(emailBuilder.getFrom());
        for (String to : emailBuilder.getTos()) {
            helper.addTo(to);
        }
        for (String cc : emailBuilder.getCcs()) {
            helper.addCc(cc);
        }
        for (String bcc : emailBuilder.getBccs()) {
            helper.addBcc(bcc);
        }
        helper.setSubject(emailBuilder.getSubject());
        helper.setText(emailBuilder.getBody(), emailBuilder.isHtml());

        // Inline
        for (EmailAttachment emailAttachment : emailBuilder.getInlineAttachments()) {
            helper.addInline(emailAttachment.getId(), emailAttachment.getResource());
        }

        // Attachment
        for (EmailAttachment emailAttachment : emailBuilder.getAttachments()) {
            helper.addAttachment(emailAttachment.getId(), emailAttachment.getResource());
        }

        mailSender.send(message);
    } catch (Exception e) {
        throw new SmallToolsException("Could not send email", e);
    }
}

From source file:com.github.dbourdette.otto.service.mail.Mailer.java

public void send(Mail mail) throws MessagingException, UnsupportedEncodingException {
    MailConfiguration configuration = findConfiguration();

    JavaMailSender javaMailSender = mailSender(configuration);

    MimeMessage mimeMessage = javaMailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "UTF-8");
    helper.setSubject(mail.getSubject());
    helper.setFrom(configuration.getSender());

    for (String name : StringUtils.split(mail.getTo(), ",")) {
        helper.addTo(name);
    }/*from w  w w. ja va  2 s.  c o m*/

    helper.setText(mail.getHtml(), true);

    javaMailSender.send(mimeMessage);
}

From source file:com.hygenics.parser.Send.java

public void run() {

    try {/*from   w w w .  jav a 2  s  .c  o  m*/
        log.info("Creating Message");
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        InternetAddress addr = new InternetAddress(fromEmails);

        helper.setFrom(addr);

        for (String email : emails) {
            helper.addTo(new InternetAddress(email));
        }

        helper.setSubject(subject);
        helper.setText(body);

        if (fpath != null) {
            log.info("Attaching File");
            File f = new File(fpath);

            if (f.exists()) {
                helper.addAttachment(fpath, f);
            }
        }

        log.info("Sending Email");
        mailSender.send(message);

    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:eu.openanalytics.shinyproxy.controllers.IssueController.java

public void sendSupportMail(IssueForm form, Proxy proxy) {
    String supportAddress = getSupportAddress();
    if (supportAddress == null)
        throw new RuntimeException("Cannot send mail: no support address configured");
    if (mailSender == null)
        throw new RuntimeException("Cannot send mail: no smtp settings configured");

    try {/*w  w w. j  a  va  2 s.  c  o m*/
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        // Headers
        helper.setFrom(environment.getProperty("proxy.support.mail-from-address", "issues@shinyproxy.io"));
        helper.addTo(supportAddress);
        helper.setSubject("ShinyProxy Error Report");

        // Body
        StringBuilder body = new StringBuilder();
        String lineSep = System.getProperty("line.separator");
        body.append(String.format("This is an error report generated by ShinyProxy%s", lineSep));
        body.append(String.format("User: %s%s", form.userName, lineSep));
        if (form.appName != null)
            body.append(String.format("App: %s%s", form.appName, lineSep));
        if (form.currentLocation != null)
            body.append(String.format("Location: %s%s", form.currentLocation, lineSep));
        if (form.customMessage != null)
            body.append(String.format("Message: %s%s", form.customMessage, lineSep));
        helper.setText(body.toString());

        // Attachments (only if container-logging is enabled)
        if (logService.isLoggingEnabled() && proxy != null) {
            Path[] filePaths = logService.getLogFiles(proxy);
            for (Path p : filePaths) {
                if (Files.exists(p))
                    helper.addAttachment(p.toFile().getName(), p.toFile());
            }
        }

        mailSender.send(message);
    } catch (Exception e) {
        throw new RuntimeException("Failed to send email", e);
    }
}

From source file:com.devnexus.ting.core.service.integration.GenericEmailToMimeMessageTransformer.java

@Transformer
public MimeMessage prepareMailToSpeaker(GenericEmail email) {

    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    MimeMessageHelper messageHelper;
    try {//from  www . j a  v  a  2 s.c o m
        messageHelper = new MimeMessageHelper(mimeMessage, true);
        messageHelper.setText(email.getText(), email.getHtml());
        messageHelper.setFrom(email.getFrom());

        for (String emailToAddress : email.getTo()) {
            messageHelper.addTo(emailToAddress);
        }

        if (!email.getCc().isEmpty()) {
            for (String emailCcAddress : email.getCc()) {
                messageHelper.addCc(emailCcAddress);
            }
        }

        messageHelper.setSubject(email.getSubject());

    } catch (MessagingException e) {
        throw new IllegalStateException("Error creating mail message for email: " + email, e);
    }

    return messageHelper.getMimeMessage();
}

From source file:cdr.forms.EmailNotificationHandler.java

private void sendReceipt(HashMap<String, Object> model, Form form, String recipient) {

    if (recipient == null || recipient.trim().length() == 0)
        return;/*from   w  w  w  . j a  v  a 2s  .c  o  m*/

    StringWriter htmlsw = new StringWriter();
    StringWriter textsw = new StringWriter();
    try {
        depositReceiptHtmlTemplate.process(model, htmlsw);
        depositReceiptTextTemplate.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);
        message.addTo(recipient);
        message.setSubject("Deposit Receipt for " + form.getTitle());
        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;
    }

}

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 www  . j  a  v  a  2 s . co  m*/

    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;
    }
}

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

public ConfigurazioneSMTPSpring() {

    TextField smtpHost = new TextField("SMTP Host Server");
    smtpHost.setRequired(true);//from w w w .  jav a2s  .  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:com.devnexus.ting.core.service.impl.CfpToMailTransformer.java

public MimeMessage prepareMailToSpeaker(CfpSubmission cfpSubmission) {

    String templateHtml = SystemInformationUtils.getCfpHtmlEmailTemplate();
    String templateText = SystemInformationUtils.getCfpTextEmailTemplate();

    String renderedHtmlTemplate = applyMustacheTemplate(cfpSubmission, templateHtml);
    String renderedTextTemplate = applyMustacheTemplate(cfpSubmission, templateText);

    MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    MimeMessageHelper messageHelper;
    try {//w w w  . ja  v  a  2 s .  c o m
        messageHelper = new MimeMessageHelper(mimeMessage, true);
        messageHelper.setText(renderedTextTemplate, renderedHtmlTemplate);

        messageHelper.setFrom(fromUser);

        for (CfpSubmissionSpeaker submissionSpeaker : cfpSubmission.getSpeakers()) {
            messageHelper.addTo(submissionSpeaker.getEmail());
        }

        if (StringUtils.hasText(this.ccUser)) {
            messageHelper.setCc(this.ccUser);
        }

        messageHelper.setSubject("DevNexus 2015 - CFP - " + cfpSubmission.getSpeakersAsString(false));

    } catch (MessagingException e) {
        throw new IllegalStateException("Error creating mail message for CFP: " + cfpSubmission, e);
    }

    return messageHelper.getMimeMessage();
}