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

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

Introduction

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

Prototype

public void setText(String text) throws MessagingException 

Source Link

Document

Set the given text directly as content in non-multipart mode or as default body part in multipart mode.

Usage

From source file:com.oak_yoga_studio.service.impl.NotificationServiceImpl.java

public void sendMail(String fromEmail, String toEmail, String emailSubject, String emailBody) {

    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {/* w ww . ja v  a  2s  .c  o  m*/
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        helper.setFrom(fromEmail);
        helper.setTo(toEmail);
        helper.setSubject(emailSubject);
        helper.setText(emailBody);

        /*
         uncomment the following lines for attachment FileSystemResource
         file = new FileSystemResource("attachment.jpg");
         helper.addAttachment(file.getFilename(), file);
         */
        javaMailSender.send(mimeMessage);
        System.out.println("Mail sent successfully.");//debugging
    } catch (MessagingException e) {
        e.printStackTrace();
    }

}

From source file:com.pamarin.income.controller.RegisterAccountCtrl.java

private void sendEmail(final String activateCode) {
    mailSender.send(new MailCallback() {

        @Override/*from w w w.j  a v  a 2 s. com*/
        public void execute(MimeMessageHelper helper) throws Exception {
            helper.setSubject("?" + app.getName());
            helper.setTo(getEmail());
            helper.setText(
                    "? "
                            + "????  "
                            + UrlUtils.buildHostUrl() + "/register/activate/?code=" + activateCode);
        }
    });
}

From source file:com.pamarin.income.controller.SuggestionCtrl.java

private void sendEmail2User() {
    mailSender.send(new MailCallback() {

        @Override//from ww  w.  java 2s.c o m
        public void execute(MimeMessageHelper helper) throws Exception {
            helper.setSubject("" + app.getName());
            helper.setText(
                    " ??");
            helper.setTo(SecurityUtils.getUser().getUsername());
        }
    });
}

From source file:org.trpr.platform.integration.impl.email.SpringMailSender.java

/**
 * Interface method implementation. Sends an email using the specified values and the configured mail sender.
 * @see org.trpr.platform.integration.spi.email.MailSender#sendMail(java.lang.String, java.lang.String[], java.lang.String, java.net.URL)
 *//*from   w w  w .j a va  2 s  .c o  m*/
public void sendMail(final String senderAddress, final String subject, final String[] recipients,
        final String message, final URL attachmentURL) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            InternetAddress[] recipientAddresses = new InternetAddress[recipients.length];
            for (int i = 0; i < recipientAddresses.length; i++) {
                recipientAddresses[i] = new InternetAddress(recipients[i]);
            }
            mimeMessage.setRecipients(Message.RecipientType.TO, recipientAddresses);
            mimeMessage.setFrom(new InternetAddress(senderAddress));
            mimeMessage.setSubject(subject);
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); // multi-part flag is set to true for accommodating attachments
            if (attachmentURL != null) {
                helper.addAttachment(attachmentURL.getFile(), new FileSystemResource(attachmentURL.toString()));
            }
            helper.setText(message);
        }
    };
    this.mailSender.send(preparator);
}

From source file:gov.nih.nci.cabig.caaers.tools.mail.CaaersJavaMailSender.java

/**
 * This method is used to send an email/*from  w  w  w  .  j a  v a 2  s  . co  m*/
 */
public void sendMail(String[] to, String[] cc, String subject, String content, String[] attachmentFilePaths) {
    if (to == null || to.length == 0 || to[0] == null) {
        return;
    }
    try {
        MimeMessage message = createMimeMessage();
        message.setSubject(subject);

        // use the true flag to indicate you need a multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        if (cc != null && cc.length > 0) {
            helper.setCc(cc);
        }
        helper.setText(content);

        for (String attachmentPath : attachmentFilePaths) {
            if (StringUtils.isNotEmpty(attachmentPath)) {
                File f = new File(attachmentPath);
                FileSystemResource file = new FileSystemResource(f);
                helper.addAttachment(file.getFilename(), file);
            }
        }
        send(message);

    } catch (Exception e) {
        if (SUPRESS_MAIL_SEND_EXCEPTION)
            return; //supress the excetion related to email sending
        throw new CaaersSystemException("Error while sending email to " + to[0], e);
    }
}

From source file:com.newinit.email.MailServiceImpl.java

/**
 * envo de email con attachments//from w  ww . ja  v a2  s.  c  o  m
 *
 * @param to correo electrnico del destinatario
 * @param subject asunto del mensaje
 * @param text cuerpo del mensaje
 * @param attachments ficheros que se anexarn al mensaje
 */
@Override
public void send(String to, String subject, String text, File... attachments) {
    // chequeo de parmetros 
    Assert.hasLength(to, "email 'to' needed");
    Assert.hasLength(subject, "email 'subject' needed");
    Assert.hasLength(text, "email 'text' needed");

    // asegurando la trazabilidad
    if (log.isDebugEnabled()) {
        final boolean usingPassword = !"".equals(mailSender.getPassword());
        log.debug("Sending email to: '" + to + "' [through host: '" + mailSender.getHost() + ":"
                + mailSender.getPort() + "', username: '" + mailSender.getUsername() + "' usingPassword:"
                + usingPassword + "].");
        log.debug("isActive: " + active);
    }
    // el servicio esta activo?
    if (!active) {
        return;
    }

    // plantilla para el envo de email
    final MimeMessage message = mailSender.createMimeMessage();

    try {
        // el flag a true indica que va a ser multipart
        final MimeMessageHelper helper = new MimeMessageHelper(message, true);

        // settings de los parmetros del envo
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setFrom(getFrom());
        helper.setText(text);

        // adjuntando los ficheros
        if (attachments != null) {
            for (int i = 0; i < attachments.length; i++) {
                FileSystemResource file = new FileSystemResource(attachments[i]);
                helper.addAttachment(attachments[i].getName(), file);
                if (log.isDebugEnabled()) {
                    log.debug("File '" + file + "' attached.");
                }
            }
        }

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

    // el envo
    this.mailSender.send(message);
}

From source file:fr.mycellar.application.user.impl.ResetPasswordRequestServiceImpl.java

@Override
public void createAndSendEmail(User user, String url) {
    // Create request
    ResetPasswordRequest request = new ResetPasswordRequest();
    request.setDateTime(new LocalDateTime());
    request.setKey(new String(Base64.encodeBase64(secureRandom.generateSeed(128), false)).substring(0, 32));
    request.setUser(user);/*from ww w .j  ava 2s .  c o  m*/
    // Merge it in repository
    resetPasswordRequestRepository.save(request);
    // Send email to email
    final String email = user.getEmail();
    final String address;
    try {
        address = url + "?key=" + URLEncoder.encode(request.getKey(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("UTF-8 encoding not supported.", e);
    }

    MimeMessagePreparator mimeMessagePreparator = new MimeMessagePreparator() {
        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setTo(email);
            helper.setFrom(configurationService.getMailAddressSender());
            helper.setSubject("Changement de mot de passe");
            helper.setText("Allez  l'adresse suivante : " + address);
        }
    };
    try {
        javaMailSender.send(mimeMessagePreparator);
    } catch (Exception e) {
        throw new RuntimeException("Cannot send email.", e);
    }
}

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

public ConfigurazioneSMTPSpring() {

    TextField smtpHost = new TextField("SMTP Host Server");
    smtpHost.setRequired(true);/*from www  .jav a2  s . 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:org.crce.interns.service.impl.EmailNotificationServiceImpl.java

/**
 * //from   w w  w.  j a  va  2s  .c o m
 * @param receivers
 * @param category
 * @param message 
 */
public void sendEmailNotification(String receivers, String category, String message) {

    if (receivers.equalsIgnoreCase(COMPS) || receivers.equalsIgnoreCase(IT) || receivers.equalsIgnoreCase(PROD)
            || receivers.equalsIgnoreCase(ELEX)) {
        String list = sendEmailDAO.fetchStreamStudents(receivers);
    } else {

        //indiwala
        intendedReceivers = intendedReceivers.concat(sendEmailDAO.fetchStudentEmailId(receivers));
    }

    String[] emailIds = intendedReceivers.split("\\s");

    javaMailSender.send(new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage)
                throws javax.mail.MessagingException, IllegalStateException, IOException {
            System.out.println("Throws Exception");
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");

            //mimeMessageHelper.setTo(request.getParameter("receiver"));
            mimeMessageHelper.setTo(emailIds);

            mimeMessageHelper.setSubject(category + "-Unread Notification-Placement Management System-CRCE");

            mimeMessageHelper.setText(message);

        }
    });

}

From source file:gov.nih.nci.cabig.caaers.esb.client.MessageNotificationService.java

public void sendMail(String[] to, String subject, String content, String attachment) throws Exception {

    MimeMessage message = caaersJavaMailSender.createMimeMessage();
    message.setSubject(subject);/*from   w w w  .  j  av a 2s  .  co  m*/
    message.setFrom(new InternetAddress(configuration.get(Configuration.SYSTEM_FROM_EMAIL)));

    // use the true flag to indicate you need a multipart message
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(to);
    helper.setText(content);

    if (attachment != null) {
        File f = new File(attachment);
        FileSystemResource file = new FileSystemResource(f);
        helper.addAttachment(file.getFilename(), file);
    }

    caaersJavaMailSender.send(message);

}