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

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

Introduction

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

Prototype

public void setSubject(String subject) throws MessagingException 

Source Link

Document

Set the subject of the message, using the correct encoding.

Usage

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);/* www .  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:net.bafeimao.umbrella.web.test.MailTests.java

@Test
public void testSendMailWithInlineImage() throws MessagingException {
    // ?,???html//from w  w  w.  jav a 2s . c  o m
    MimeMessage mailMessage = senderImpl.createMimeMessage();
    // ?boolean,?MimeMessageHelpertrue?
    // multipart?
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true);

    // 
    messageHelper.setTo("29283212@qq.com");
    messageHelper.setFrom("29283212@qq.com");
    messageHelper.setSubject("!?");
    // true ?HTML?
    messageHelper.setText("<html><head></head><body><h1>hello!!spring image html mail</h1>"
            + "<img src=\"cid:aaa\"/></body></html>", true);

    FileSystemResource img = new FileSystemResource(new File(imagePath));

    messageHelper.addInline("aaa", img);

    // ??
    senderImpl.send(mailMessage);

    System.out.println("???..");
}

From source file:net.bafeimao.umbrella.web.test.MailTests.java

@Test
public void testSendMailWithAttachedImage() throws MessagingException {
    // ?,???html//www  . j av  a2 s  .  co m
    MimeMessage mailMessage = senderImpl.createMimeMessage();
    // ?boolean,?MimeMessageHelpertrue?
    // multipart? true?? ?html?
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");

    // 
    messageHelper.setTo("29283212@qq.com");
    messageHelper.setFrom("29283212@qq.com");
    messageHelper.setSubject("!?");
    // true ?HTML?
    messageHelper.setText(
            "<html><head></head><body><h1>?</h1></body></html>", true);

    FileSystemResource file = new FileSystemResource(new File(imagePath));
    // ???
    messageHelper.addAttachment("image", file);

    // ??
    senderImpl.send(mailMessage);

    System.out.println("???..");
}

From source file:com.gcrm.util.mail.MailService.java

public void sendHtmlMail(String from, String[] to, String subject, String text, String[] fileNames,
        File[] files) throws Exception {
    List<EmailSetting> emailSettings = baseService.getAllObjects(EmailSetting.class.getSimpleName());
    EmailSetting emailSetting = null;/*from ww w.ja v  a  2  s  .co  m*/
    if (emailSettings != null && emailSettings.size() > 0) {
        emailSetting = emailSettings.get(0);
    } else {
        return;
    }
    if (from == null) {
        from = emailSetting.getFrom_address();
    }
    Session mailSession = createSmtpSession(emailSetting);

    if (mailSession != null) {
        Transport transport = mailSession.getTransport();
        MimeMessage msg = new MimeMessage(mailSession);
        MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text, true);
        if (fileNames != null && files != null) {
            String fileName = null;
            File file = null;
            for (int i = 0; i < fileNames.length; i++) {
                fileName = fileNames[i];
                file = files[i];
                if (fileName != null && file != null) {
                    helper.addAttachment(fileName, file);
                }
            }
        }
        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
    }

}

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

public ConfigurazioneSMTPSpring() {

    TextField smtpHost = new TextField("SMTP Host Server");
    smtpHost.setRequired(true);//  w  w  w  .j  a  v  a2  s  . com
    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.sharetask.service.MailServiceImpl.java

@Override
public void sendEmail(final String from, final List<String> to, final String subject, final String msg,
        final int retry) {
    final MimeMessage message = mailSender.createMimeMessage();
    final MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");

    try {//from   ww  w.  j a v  a 2s.  c o  m
        helper.setFrom(noreplyMail);
        helper.setTo(to.toArray(new String[] {}));
        helper.setSubject(subject);
        helper.setText(msg, true /* html */);
        log.debug("Sending mail to:{} content:{}", to, msg);
        mailSender.send(message);
    } catch (final MailException ex) {
        log.error("Problem in sending email notification:", ex);
        notificationQueueService.storeInvitation(noreplyMail, to, subject, msg, retry + 1);
    } catch (final MessagingException e) {
        throw new IllegalStateException("Wrong mail message format: ", e);
    }
}

From source file:com.miserablemind.butter.domain.service.email.EmailService.java

/**
 * Sends a mime mail with a specified Velocity template that may contain HTML and attachments.
 *
 * @param emailMessage prepared message object to be sent. Usually prepared by {@link EmailManager}
 *///w ww .j  av a  2 s . co  m
public void sendMimeMail(final EmailMessage emailMessage) {

    MimeMessagePreparator preparedMessage = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {

            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);

            message.setTo(emailMessage.getToEmail());
            message.setFrom(emailMessage.getFromAddress());
            message.setReplyTo(emailMessage.getFromAddress());
            message.setSubject(emailMessage.getSubject());
            String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    emailMessage.getTemplatePath(), "UTF-8", emailMessage.getModel());

            message.setText(body, true);

            if (!StringUtils.isBlank(emailMessage.getAttachmentPath())) {
                FileSystemResource file = new FileSystemResource(emailMessage.getAttachmentPath());
                message.addAttachment(emailMessage.getAttachmentName(), file);
            }
        }
    };

    try {
        this.mailSender.send(preparedMessage);
    } catch (MailException e) {
        logger.error("Email Service Exception Send Mime Mail: " + e.getMessage(), e);
    }

}

From source file:nl.surfnet.coin.shared.service.ErrorMessageMailer.java

private MimeMessageHelper addSubject(MimeMessageHelper helper, ErrorMail errorMail) throws MessagingException {
    String subject = MessageFormat.format(MESSAGE_SUBJECT, errorMail.getComponent(), errorMail.getServer(),
            errorMail.getShortMessage());
    helper.setSubject(subject);
    return helper;
}

From source file:org.beanfuse.notification.mail.AbstractMailNotifier.java

public void sendMessage(Message msg) throws NotificationException {
    // contruct a MailMessage
    MailMessage mailConext = null;/*  w ww.j  a  v a  2 s .  c om*/
    if (msg instanceof MailMessage) {
        mailConext = (MailMessage) msg;
    } else {
        mailConext = new MailMessage();
        mailConext.setSubject(msg.getSubject());
        mailConext.setText(msg.getText());
        mailConext.setProperties(msg.getProperties());
        String[] to = new String[msg.getRecipients().size()];
        msg.getRecipients().toArray(to);
        mailConext.setTo(to);
    }

    MimeMessage mimeMsg = javaMailSender.createMimeMessage();
    try {
        mimeMsg.setSentDate(new Date());
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMsg);
        messageHelper.setText(buildText(mailConext), Message.HTML.equals(mailConext.getContentType()));
        String subject = buildSubject(mailConext);
        messageHelper.setSubject(subject);
        messageHelper.setFrom(fromMailbox, fromName);
        addRecipient(mimeMsg, javax.mail.Message.RecipientType.TO, mailConext.getTo());
        addRecipient(mimeMsg, javax.mail.Message.RecipientType.CC, mailConext.getCc());
        addRecipient(mimeMsg, javax.mail.Message.RecipientType.BCC, mailConext.getBcc());
        beforeSend(mailConext, mimeMsg);
        if (mimeMsg.getAllRecipients() != null && ((Address[]) mimeMsg.getAllRecipients()).length > 0) {
            javaMailSender.send(mimeMsg);
            logger.info("mail sended from {} to {} with subject {}",
                    new Object[] { fromMailbox, mailConext.getRecipients(), subject });
        }
    } catch (AddressException ex) {
        throw new NotificationException("Exception while sending message.", ex);
    } catch (MessagingException ex) {
        throw new NotificationException("Exception while sending message.", ex);
    } catch (UnsupportedEncodingException ex) {
        throw new NotificationException("Exception while sending message.", ex);
    }
    afterSend(mailConext, mimeMsg);
}

From source file:net.groupbuy.service.impl.MailServiceImpl.java

public void send(String smtpFromMail, String smtpHost, Integer smtpPort, String smtpUsername,
        String smtpPassword, String toMail, String subject, String templatePath, Map<String, Object> model,
        boolean async) {
    Assert.hasText(smtpFromMail);//w ww  .  j av  a 2 s  .c  o m
    Assert.hasText(smtpHost);
    Assert.notNull(smtpPort);
    Assert.hasText(smtpUsername);
    Assert.hasText(smtpPassword);
    Assert.hasText(toMail);
    Assert.hasText(subject);
    Assert.hasText(templatePath);
    try {
        Setting setting = SettingUtils.get();
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Template template = configuration.getTemplate(templatePath);
        String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
        javaMailSender.setHost(smtpHost);
        javaMailSender.setPort(smtpPort);
        javaMailSender.setUsername(smtpUsername);
        javaMailSender.setPassword(smtpPassword);
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, "utf-8");
        mimeMessageHelper.setFrom(MimeUtility.encodeWord(setting.getSiteName()) + " <" + smtpFromMail + ">");
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setTo(toMail);
        mimeMessageHelper.setText(text, true);
        if (async) {
            addSendTask(mimeMessage);
        } else {
            javaMailSender.send(mimeMessage);
        }
    } catch (TemplateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}