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, int multipartMode) throws MessagingException 

Source Link

Document

Create a new MimeMessageHelper for the given MimeMessage, in multipart mode (supporting alternative texts, inline elements and attachments) if requested.

Usage

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  ww.  j a  v  a  2 s.  c om
        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:ar.com.zauber.commons.message.impl.mail.MimeEmailNotificationStrategy.java

/** @see NotificationStrategy#execute(NotificationAddress[], Message) */
public final void execute(final NotificationAddress[] addresses, final Message message) {
    try {//from   w ww  .j  av  a2  s.c om
        final MailSender mailSender = getMailSender();
        //This is ugly....but if it is not a JavaMailSender it will
        //fail (for instance during tests). And the only way to
        //create a Multipartemail is through JavaMailSender
        if (mailSender instanceof JavaMailSender) {
            final JavaMailSender javaMailSender = (JavaMailSender) mailSender;
            final MimeMessage mail = javaMailSender.createMimeMessage();
            final MimeMessageHelper helper = new MimeMessageHelper(mail, true);
            helper.setFrom(getFromAddress().getEmailStr());
            helper.setTo(SimpleEmailNotificationStrategy.getEmailAddresses(addresses));
            helper.setReplyTo(getEmailAddress(message.getReplyToAddress()));
            helper.setSubject(message.getSubject());
            setContent(helper, (MultipartMessage) message);
            addHeaders(message, mail);
            javaMailSender.send(mail);
        } else {
            final SimpleMailMessage mail = new SimpleMailMessage();
            mail.setFrom(getFromAddress().getEmailStr());
            mail.setTo(getEmailAddresses(addresses));
            mail.setReplyTo(getEmailAddress(message.getReplyToAddress()));
            mail.setSubject(message.getSubject());
            mail.setText(message.getContent());
            mailSender.send(mail);
        }
    } catch (final MessagingException e) {
        throw new RuntimeException("Could not send message", e);
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException("Could not send message", e);
    }

}

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

/**
 * envo de email con attachments//w w  w . java2 s .com
 *
 * @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:nl.surfnet.coin.shared.service.ErrorMessageMailer.java

private MimeMessageHelper createMessage() {
    MimeMessage message = mailSender.createMimeMessage();
    return new MimeMessageHelper(message, "UTF-8");
}

From source file:org.smigo.user.MailHandler.java

public void sendAdminNotificationHtml(String subject, String text) {
    try {/*  w ww.j a  v a 2  s  . c  om*/
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setText(text, true);
        helper.setTo(notifierEmail);
        helper.setFrom(mailSenderUsername);
        helper.setSubject("[SMIGO] " + subject);
        senderExecutor.execute(() -> mailSender.send(message));
    } catch (MessagingException e) {
        log.error("Send message failed:" + text, e);
    }
}

From source file:org.jnap.core.email.Email.java

public void prepare(MimeMessage mimeMessage) throws Exception {
    final EmailAccountInfo acc = getAccountInfo();
    boolean multipart = StringUtils.isNotBlank(getHtmlText())
            || (getInlineResources() != null && getInlineResources().size() > 0)
            || (getAttachments() != null && getAttachments().size() > 0);

    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, multipart);
    if (acc.getFromName() != null) {
        helper.setFrom(acc.getFromEmailAddress(), acc.getFromName());
    } else {// www  .j  av a 2s.  c  o  m
        this.setFrom(acc.getFromEmailAddress());
    }
    helper.setTo(getTo());
    if (getCc() != null) {
        helper.setCc(getCc());
    }
    if (getBcc() != null) {
        helper.setBcc(getBcc());
    }
    helper.setSentDate(new Date());
    mimeMessage.setSubject(getMessage(getSubject()), this.encoding);

    // sender info
    if (acc != null && StringUtils.isNotBlank(acc.getFromName())) {
        helper.setFrom(acc.getFromEmailAddress(), getMessage(acc.getFromName()));
    } else {
        helper.setFrom(acc.getFromEmailAddress());
    }
    if (acc != null && StringUtils.isNotBlank(acc.getReplyToEmailAddress())) {
        if (StringUtils.isNotBlank(acc.getReplyToName())) {
            helper.setReplyTo(acc.getReplyToEmailAddress(), acc.getReplyToName());
        } else {
            helper.setReplyTo(acc.getReplyToEmailAddress());
        }
    }

    final boolean hasHtmlText = StringUtils.isNotBlank(getHtmlText());
    final boolean hasText = StringUtils.isNotBlank(getText());
    if (hasHtmlText && hasText) {
        helper.setText(getText(), getHtmlText());
    } else if (hasHtmlText || hasText) {
        helper.setText(hasHtmlText ? getHtmlText() : getText());
    }

    // set headers
    final Map<String, String> mailHeaders = this.getHeaders();
    for (String header : mailHeaders.keySet()) {
        mimeMessage.addHeader(header, mailHeaders.get(header));
    }

    // add inline resources
    final Map<String, Resource> inlineRes = this.getInlineResources();
    if (inlineRes != null) {
        for (String cid : inlineRes.keySet()) {
            helper.addInline(cid, inlineRes.get(cid));
        }
    }
    // add attachments
    final Map<String, Resource> attachments = this.getAttachments();
    if (attachments != null) {
        for (String attachmentName : attachments.keySet()) {
            helper.addAttachment(attachmentName, attachments.get(attachmentName));
        }
    }
}

From source file:org.cgiar.dapa.ccafs.tpe.service.impl.TPEMailService.java

@Override
public void notifyAdmin(final Map<String, Object> templateVariables) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
            message.setTo(supportEmail);
            message.setFrom(new InternetAddress(adminEmail));
            message.setSubject(SUBJECT_ADMIN);
            String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "templates/notify-admin.vm", "UTF-8", templateVariables);
            log.info(body);//from w w w.j  a v a  2 s  . c o m
            message.setText(body, true);
        }
    };
    this.mailSender.send(preparator);

}

From source file:com.sisrni.service.FreeMarkerMailServiceImpl.java

private MimeMessagePreparator getMessagePreparator(final Object obj) throws Exception {

    try {/*w  ww.  j  a  v a  2 s .  c  o  m*/

        MimeMessagePreparator preparator = new MimeMessagePreparator() {

            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

                helper.setSubject(getSubJect());
                //helper.setFrom("tgraduacion01@gmail.com" );
                helper.setTo(getSetToMail());
                helper.setSentDate(new Date());

                Map<String, Object> model = new HashMap<String, Object>();
                model.put("obj", obj);

                String text = geFreeMarkerTemplateContent(model);
                System.out.println("Contenido de plantilla : " + text);

                // use the true flag to indicate you need a multipart message
                helper.setText(text, true);

                //Additionally, let's add a resource as an attachment as well.
                //helper.addAttachment("cutie.png", new ClassPathResource("linux-icon.png"));
            }
        };
        return preparator;
    } catch (Exception ex) {
        throw new Exception(
                "Error class  FreeMarkerMailServiceImpl - getMessagePreparator()\n" + ex.getMessage(),
                ex.getCause());
    }

}

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

@Override
public void sendEmailWithAttachment(ReportMailingJobEmailData reportMailingJobEmailData) {
    try {/*w w w.j  a  v a2  s  .  c  om*/
        // 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:com.baomidou.framework.mail.MailHelper.java

/**
 * ??/* w ww  .  ja  va 2  s.c om*/
 * 
 * @param personal
 *            ??????
 * @param from
 *            ???
 * @param to
 *            ???
 * @param subject
 *            
 * @param tplName
 *            ???xxx.vm  ??/WEB-INF/views/mail/..
 * @param data
 *            ???
 * @return
 */
public boolean sendMail(String personal, String from, String[] to, String subject, String tplName,
        Map<String, Object> data) {
    try {
        MimeMessage msg = mailSender.createMimeMessage();
        MimeMessageHelper msgHelper = new MimeMessageHelper(msg, getCharset());
        msgHelper.setFrom(from, personal);
        msgHelper.setTo(to);
        msgHelper.setSubject(subject);
        msgHelper.setText(this.getHtmltext(tplName, data), true);
        mailSender.send(msg);
        return true;
    } catch (Exception e) {
        logger.error("send mail error.", e);
    }
    return false;
}