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:jp.co.opentone.bsol.linkbinder.service.notice.impl.SendMailServiceImpl.java

public boolean sendMail(EmailNotice emailNotice) {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message);

    try {//from w  w w  . j  av a 2 s .  c  om
        helper.setSubject(emailNotice.getMhSubject());
        helper.setText(emailNotice.getMailBody());

        String[] addresses = convertEmpNoToMailAddress(emailNotice.getMhTo());
        if (addresses.length == 0) {
            LOG.warn(
                    "to???????????????????"
                            + "??????email_notice.id = {}",
                    emailNotice.getId());
            return false;
        }
        helper.setBcc(addresses);

        //            String [] from = convertEmpNoToMailAddress(emailNotice.getMhFrom());
        //            if (from.length == 0) {
        //                LOG.warn("from???????????????????"
        //                        + "??????email_notice.id = {}", emailNotice.getId());
        //                return false;
        //            }
        helper.setFrom(emailNotice.getMhFrom());

        mailSender.send(message);

        return true;
    } catch (MessagingException e) {
        LOG.warn("??????", e);
        return false;
    }
}

From source file:eu.openanalytics.rsb.component.EmailDepositHandlerTestCase.java

@Test
public void handleJob() throws Exception {
    final MimeMessage mimeMessage = new MimeMessage((Session) null);
    final MimeMessageHelper mmh = new MimeMessageHelper(mimeMessage, true);
    mmh.setReplyTo("test@test.com");
    mmh.setText("test job");
    mmh.addAttachment("r-job-sample.zip", new ClassPathResource("data/r-job-sample.zip"),
            Constants.ZIP_CONTENT_TYPE);

    final DepositEmailConfiguration depositEmailConfiguration = mock(PersistedDepositEmailConfiguration.class);
    when(depositEmailConfiguration.getApplicationName()).thenReturn(TEST_APPLICATION_NAME);
    final Message<MimeMessage> message = MessageBuilder.withPayload(mimeMessage)
            .setHeader(EmailDepositHandler.EMAIL_CONFIG_HEADER_NAME, depositEmailConfiguration).build();

    emailDepositHandler.handleJob(message);

    final ArgumentCaptor<MultiFilesJob> jobCaptor = ArgumentCaptor.forClass(MultiFilesJob.class);
    verify(messageDispatcher).dispatch(jobCaptor.capture());

    final MultiFilesJob job = jobCaptor.getValue();
    assertThat(job.getApplicationName(), is(TEST_APPLICATION_NAME));
    assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_SUBJECT_META_NAME), is(true));
    assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_ADDRESSEE_META_NAME), is(true));
    assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_REPLY_TO_META_NAME), is(true));
    assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_REPLY_CC_META_NAME), is(true));
    assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_BODY_META_NAME), is(true));
    assertThat(job.getSource(), is(Source.EMAIL));
    job.destroy();/*from w  ww  . j  a  v a2  s.  c  o m*/
}

From source file:net.maritimecloud.identityregistry.utils.EmailUtil.java

public void sendBugReport(BugReport report) throws MailException, MessagingException {
    MimeMessage message = this.mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(bugReportEmail);//from  w  w w .j  a v  a 2s. c om
    helper.setFrom(from);
    helper.setSubject(report.getSubject());
    helper.setText(report.getDescription());
    if (report.getAttachments() != null) {
        for (BugReportAttachment attachment : report.getAttachments()) {
            // Decode base64 encoded data
            byte[] data = Base64.getDecoder().decode(attachment.getData());
            ByteArrayDataSource dataSource = new ByteArrayDataSource(data, attachment.getMimetype());
            helper.addAttachment(attachment.getName(), dataSource);
        }
    }
    this.mailSender.send(message);
}

From source file:com.rinxor.cloud.service.mail.Mailer.java

public void sendMail(String dear, String content) {

    MimeMessage message = mailSender.createMimeMessage();

    try {/*from  www.  jav a  2s .c o  m*/
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom(simpleMailMessage.getFrom());
        helper.setTo(simpleMailMessage.getTo());
        helper.setSubject(simpleMailMessage.getSubject());
        helper.setText(String.format(simpleMailMessage.getText(), dear, content));

        //FileSystemResource file = new FileSystemResource("C:\\log.txt");
        //helper.addAttachment(file.getFilename(), file);
    } catch (MessagingException e) {
        throw new MailParseException(e);
    }
    mailSender.send(message);
}

From source file:org.pegadi.server.mail.MailServerImpl.java

public boolean sendmail(String from, List<String> to, String subject, String text) {

    MimeMessage msg = this.mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(msg, "UTF-8");

    try {/*from w  w  w .j a v  a2s  .  c  om*/
        helper.setTo(to.toArray(new String[to.size()]));
        helper.setFrom(from);
        helper.setBcc(from);
        helper.setSubject(subject);
        helper.setText(text);
        mailSender.send(msg);
        log.info("Sent mail: From: " + from + ", To: " + to + ", Subject: " + subject);
    } catch (MessagingException ex) {
        log.error("Can't send mail", ex);
        return false;
    }
    return true;
}

From source file:uk.org.funcube.fcdw.server.email.VelocityTemplateEmailSender.java

@Override
public void sendEmailUsingTemplate(final String fromAddress, final String toAddress,
        final String[] bccAddresses, final String subject, final String templateLocation,
        final Map<String, Object> model) {

    final Map<String, Object> augmentedModel = new HashMap<String, Object>(model);
    augmentedModel.put("dateTool", new DateTool());
    augmentedModel.put("numberTool", new NumberTool());
    augmentedModel.put("mathTool", new MathTool());

    final Writer writer = new StringWriter();
    VelocityEngineUtils.mergeTemplate(velocityEngine, templateLocation, augmentedModel, writer);
    final String emailBody = writer.toString();

    final MimeMessagePreparator prep = new MimeMessagePreparator() {
        @Override/*from  w  ww . j  a v a  2s. co m*/
        public void prepare(final MimeMessage mimeMessage) throws Exception {
            final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, EMAIL_CONTENT_ENCODING);
            message.setTo(toAddress);
            message.setFrom(fromAddress);
            message.setSubject(subject);
            message.setText(emailBody);

            if (!ArrayUtils.isEmpty(bccAddresses)) {
                message.setBcc(bccAddresses);
            }
        }
    };

    try {
        mailSender.send(prep);
        LOGGER.debug(String.format("Sent %3$s email To: %1$s, Bcc: %2$s", toAddress,
                ArrayUtils.toString(bccAddresses, "None"), templateLocation));
    } catch (final MailException e) {
        LOGGER.error("Could not send email " + subject, e);
        throw e;
    }
}

From source file:com.gst.infrastructure.reportmailingjob.service.ReportMailingJobEmailServiceImpl.java

@Override
public void sendEmailWithAttachment(ReportMailingJobEmailData reportMailingJobEmailData) {
    try {//from w  w  w  . j a va 2s.co  m
        // get all ReportMailingJobConfiguration objects from the database
        this.reportMailingJobConfigurationDataCollection = this.reportMailingJobConfigurationReadPlatformService
                .retrieveAllReportMailingJobConfigurations();

        JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
        javaMailSenderImpl.setHost(this.getGmailSmtpServer());
        javaMailSenderImpl.setPort(this.getGmailSmtpPort());
        javaMailSenderImpl.setUsername(this.getGmailSmtpUsername());
        javaMailSenderImpl.setPassword(this.getGmailSmtpPassword());
        javaMailSenderImpl.setJavaMailProperties(this.getJavaMailProperties());

        MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();

        // use the true flag to indicate you need a multipart message
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

        mimeMessageHelper.setTo(reportMailingJobEmailData.getTo());
        mimeMessageHelper.setText(reportMailingJobEmailData.getText());
        mimeMessageHelper.setSubject(reportMailingJobEmailData.getSubject());

        if (reportMailingJobEmailData.getAttachment() != null) {
            mimeMessageHelper.addAttachment(reportMailingJobEmailData.getAttachment().getName(),
                    reportMailingJobEmailData.getAttachment());
        }

        javaMailSenderImpl.send(mimeMessage);
    }

    catch (MessagingException e) {
        // handle the exception
        e.printStackTrace();
    }
}

From source file:cs544.wamp_blog_engine.service.impl.NotificationService.java

public void sendMail(String fromEmail, String toEmail, String emailSubject, String emailBody) {
    //      String fromEmail = emailTemplate.getFrom();
    //      String[] toEmail = emailTemplate.getTo();
    //        String[] toEmails = new String[]{toEmail};
    //      String emailSubject = emailTemplate.getSubject();
    //      String emailBody = String.format(emailTemplate.getText(), dear, content);

    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {/* w w  w.j  a v a2s  .  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.");
    } catch (MessagingException e) {
        e.printStackTrace();
    }

}

From source file:com.autentia.wuija.mail.MailService.java

/**
 * send an e-mail//from w w  w . j  ava 2  s. co m
 * 
 * @param to recipient e-mail
 * @param subject the subject of the e-mail
 * @param text the body of the e-mail
 * @param attachments an array of it
 * @throws EmailException if the e-mail cannot be prepare or send.
 */
public void send(String to, String subject, String text, File... attachments) {
    Assert.hasLength(to, "email 'to' needed");
    Assert.hasLength(subject, "email 'subject' needed");
    Assert.hasLength(text, "email 'text' needed");

    if (log.isDebugEnabled()) {
        final boolean usingPassword = StringUtils.isNotBlank(mailSender.getPassword());
        log.debug("Sending email to: '" + to + "' [through host: '" + mailSender.getHost() + ":"
                + mailSender.getPort() + "', username: '" + mailSender.getUsername() + "' usingPassword:"
                + usingPassword + "].");
        log.debug("isActive: " + active);
    }
    if (!active) {
        return;
    }

    final MimeMessage message = mailSender.createMimeMessage();

    try {
        // use the true flag to indicate you need a multipart message
        final MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setFrom(getFrom());
        helper.setText(text);

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

    } catch (MessagingException e) {
        final String msg = "Cannot prepare email message : " + subject + ", to: " + to;
        log.error(msg, e);
        throw new MailPreparationException(msg, e);
    }
    this.mailSender.send(message);
}

From source file:fr.mycellar.application.contact.impl.ContactServiceImpl.java

@Override
@Scheduled(cron = "0 0 0 * * *")
public void sendReminders() {
    final String[] to = configurationService.getReminderAddressReceivers();
    if (to.length == 0) {
        return;//from ww w.j av  a2s  . c  o  m
    }
    final StringBuilder content = new StringBuilder();
    List<Contact> contacts = contactRepository.getAllToContact();
    if ((contacts != null) && (contacts.size() > 0)) {
        for (Contact contact : contacts) {
            content.append("Domaine ").append(contact.getProducer().getName()).append("  recontacter le ")
                    .append(contact.getNext().toString("dd/MM/yyyy")).append("\r\n");
            content.append("Dernier contact le ").append(contact.getCurrent().toString("dd/MM/yyyy"))
                    .append(" :").append("\r\n").append(contact.getText()).append("\r\n");
            content.append("------------------------------------------------").append("\r\n");
        }
        final String from = configurationService.getMailAddressSender();
        MimeMessagePreparator mimeMessagePreparator = new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
                helper.setFrom(from);
                helper.setSubject("Contacts  recontacter");
                helper.setText(content.toString());
                helper.setTo(to);
            }
        };
        try {
            javaMailSender.send(mimeMessagePreparator);
        } catch (Exception e) {
            throw new RuntimeException("Cannot send email.", e);
        }
    }
}