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

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

Introduction

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

Prototype

public void setFrom(String from) throws MessagingException 

Source Link

Usage

From source file:thymeleafexamples.springmail.service.EmailService.java

public void sendMailWithAttachment(final String recipientName, final String recipientEmail,
        final String attachmentFileName, final byte[] attachmentBytes, final String attachmentContentType,
        final Locale locale) throws MessagingException {

    // Prepare the evaluation context
    final Context ctx = new Context(locale);
    ctx.setVariable("name", recipientName);
    ctx.setVariable("subscriptionDate", new Date());
    ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));

    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true /* multipart */, "UTF-8");
    message.setSubject("Example HTML email with attachment");
    message.setFrom("thymeleaf@example.com");
    message.setTo(recipientEmail);/*from  ww w .ja va  2  s.c  o m*/

    // Create the HTML body using Thymeleaf
    final String htmlContent = this.templateEngine.process("email-withattachment.html", ctx);
    message.setText(htmlContent, true /* isHtml */);

    // Add the attachment
    final InputStreamSource attachmentSource = new ByteArrayResource(attachmentBytes);
    message.addAttachment(attachmentFileName, attachmentSource, attachmentContentType);

    // Send mail
    this.mailSender.send(mimeMessage);

}

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

public void handleResult(final MultiFilesResult result) throws MessagingException, IOException {
    final Serializable responseBody = result.getMeta().get(EMAIL_BODY_META_NAME);
    final String responseText = responseBody instanceof File ? FileUtils.readFileToString((File) responseBody)
            : responseBody.toString();/*from   ww  w .  ja  v  a2s .c  o  m*/

    final MimeMessage mimeMessage = mailSender.createMimeMessage();
    final MimeMessageHelper mmh = new MimeMessageHelper(mimeMessage, true);

    mmh.setFrom((String) result.getMeta().get(EMAIL_ADDRESSEE_META_NAME));
    mmh.setTo((String) result.getMeta().get(EMAIL_REPLY_TO_META_NAME));
    mmh.setCc((String[]) result.getMeta().get(EMAIL_REPLY_CC_META_NAME));
    mmh.setSubject("RE: " + result.getMeta().get(EMAIL_SUBJECT_META_NAME));

    if (result.isSuccess()) {
        mmh.setText(responseText);
        for (final File resultFile : result.getPayload()) {
            mmh.addAttachment(resultFile.getName(), resultFile);
        }
    } else {
        mmh.setText(FileUtils.readFileToString(result.getPayload()[0]));
    }

    final Message<MimeMailMessage> message = new GenericMessage<MimeMailMessage>(new MimeMailMessage(mmh));
    outboundEmailChannel.send(message);
}

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

/**
 * envo de email con attachments/*from   www.  j  a  v  a  2 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:br.com.semanticwot.cd.infra.MailManager.java

public void sendNewPurchaseMail(SystemUser user, String emailTemplate) throws MessagingException {

    Object[] args = { user.getName(), user.getUsername() };
    MessageFormat fmt = new MessageFormat(emailTemplate);

    MimeMessage message = mailer.createMimeMessage();

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

    // use the true flag to indicate the text included is HTML
    helper.setText(fmt.format(args), true);

    System.out.println("Passei por aqui " + user.getUsername());

    //SimpleMailMessage email = new SimpleMailMessage();
    helper.setFrom(user.getUsername());

    // Somente por enquanto, que esta em teste. 
    // Em producao mudar para helper.setTo(user.getLogin());
    helper.setTo("notlian.junior@gmail.com");

    helper.setSubject("PSWoT Register");
    mailer.send(message);/*  ww  w.  j  ava2s. co m*/
}

From source file:gr.abiss.calipso.service.EmailService.java

@Async
public void sendEmail(final String subject, final String templateName, String emailTo, String emailFrom,
        final Context ctx) {
    try {// w  w  w  . j  a  v a  2 s  .  c  o m
        // Prepare message using a Spring helper
        final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
        message.setSubject(subject);
        message.setFrom(emailFrom);
        message.setTo(emailTo);
        ctx.setVariable("baseUrl", this.baseUrl);
        // Create the HTML body using Thymeleaf
        final String htmlContent = this.templateEngine.process(templateName, ctx);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending email body: " + htmlContent);
        }
        message.setText(htmlContent, true /* isHtml */);

        // Send email
        if (StringUtils.isNotBlank(ConfigurationFactory.getConfiguration().getString("mail.server.host"))) {
            this.mailSender.send(mimeMessage);
        } else {
            LOGGER.warn("Skipped sending email as mail.server.host property is empty");
        }
    } catch (Exception e) {
        LOGGER.error("Failed to send email: ", e);
    }

}

From source file:csns.util.EmailUtils.java

public boolean sendHtmlMail(Email email) {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message);

    try {/*from w  w  w  .  ja v  a 2 s.com*/
        message.setContent(getHtml(email), "text/html");

        helper.setSubject(email.getSubject());
        helper.setFrom(email.getAuthor().getPrimaryEmail());
        helper.setCc(email.getAuthor().getPrimaryEmail());
        String addresses[] = getAddresses(email.getRecipients(), email.isUseSecondaryEmail())
                .toArray(new String[0]);
        if (addresses.length > 1) {
            helper.setTo(appEmail);
            helper.setBcc(addresses);
        } else
            helper.setTo(addresses);

        mailSender.send(message);

        logger.info(email.getAuthor().getUsername() + " sent email to "
                + StringUtils.arrayToCommaDelimitedString(addresses));

        return true;
    } catch (MessagingException e) {
        logger.warn("Fail to send MIME message", e);
    }

    return false;
}

From source file:ru.mystamps.web.service.MailServiceImpl.java

@SuppressWarnings("PMD.UseObjectForClearerAPI")
private void sendMail(final String email, final String subject, final String text, final String tag) {

    try {//from  ww w .  j av a 2s.c o m
        // We're using MimeMessagePreparator only because of its capability of adding headers.
        // Otherwise we would use SimpleMailMessage class.
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            @Override
            @SuppressWarnings("PMD.SignatureDeclareThrowsException")
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
                message.setValidateAddresses(true);
                message.setTo(email);
                message.setFrom(new InternetAddress(robotEmail, "My Stamps", "UTF-8"));
                message.setSubject(subject);
                message.setText(text);

                // see: http://documentation.mailgun.com/user_manual.html#sending-via-smtp
                message.getMimeMessage().addHeader("X-Mailgun-Tag", tag);
                if (testMode) {
                    message.getMimeMessage().addHeader("X-Mailgun-Drop-Message", "yes");
                }
            }
        };

        mailer.send(preparator);

    } catch (MailException ex) {
        throw new EmailSendingException("Can't send mail to e-mail " + email, ex);
    }
}

From source file:no.dusken.common.control.MailController.java

/**
 *
 * @param mail the mail part of the mail
 * @param model other things that should be in the mail.
 * @param template - the path to the velocitytemplate to use (mail/template.vm)
 *//*  ww  w .j  a  va2 s .c o  m*/
public void sendEmail(final Mail mail, final Map model, final String template) {
    final Map<String, Object> map = new HashMap<String, Object>();
    if (model != null) {
        map.putAll(model);
    }
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo(mail.getToAddress());
            if (mail.getFromAddress() == null || mail.getFromAddress().equals("")) {
                mail.setFromAddress(defaultSenderAddress);
            }
            message.setFrom(mail.getFromAddress());
            message.setSubject(mail.getSubject());

            map.put("mail", mail);
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, map);
            message.setText(text, false);
            if (mail.getAttachment() != null) {
                FileSystemResource res = new FileSystemResource(mail.getAttachment());
                message.addAttachment(mail.getAttachment().getName(), res);
            }
        }
    };
    this.mailSender.send(preparator);
}

From source file:cz.zcu.kiv.eegdatabase.data.service.SpringJavaMailService.java

protected MimeMessage createMimeMessage(String from, String to, String subject, String emailBody)
        throws MailException {
    try {//from  w  ww  . ja  va 2  s . c o m
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
        message.setFrom(from);
        // message.setContent("text/html");
        message.setTo(to);
        message.setSubject(subject);
        message.setText(emailBody, true);
        log.debug("Message " + message);
        return mimeMessage;
    } catch (MessagingException e) {// rethrow as MailException
        throw new MailPreparationException(e.getMessage(), e);
    }
}

From source file:cn.edu.zjnu.acm.judge.user.ResetPasswordController.java

@PostMapping("/resetPassword")
public void doPost(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "action", required = false) String action,
        @RequestParam(value = "verify", required = false) String verify,
        @RequestParam(value = "username", required = false) String username, Locale locale) throws IOException {
    response.setContentType("text/javascript;charset=UTF-8");
    PrintWriter out = response.getWriter();

    HttpSession session = request.getSession(false);
    String word = null;//  w  ww.jav  a 2 s  .  c  o  m
    if (session != null) {
        word = (String) session.getAttribute("word");
        session.removeAttribute("word");
    }
    if (word == null || !word.equalsIgnoreCase(verify)) {
        out.print("alert('??');");
        return;
    }

    User user = userMapper.findOne(username);
    if (user == null) {
        out.print("alert('?');");
        return;
    }
    String email = user.getEmail();
    if (email == null || !email.toLowerCase().matches(ValueCheck.EMAIL_PATTERN)) {
        out.print(
                "alert('???????');");
        return;
    }
    try {
        String vc = user.getVcode();
        if (vc == null || user.getExpireTime() != null && user.getExpireTime().compareTo(Instant.now()) < 0) {
            vc = Utility.getRandomString(16);
        }
        user = user.toBuilder().vcode(vc).expireTime(Instant.now().plus(1, ChronoUnit.HOURS)).build();
        userMapper.update(user);
        String url = getPath(request, "/resetPassword.html?vc=", vc + "&u=", user.getId());
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("url", url);
        map.put("ojName", judgeConfiguration.getContextPath() + " OJ");

        String content = templateEngine.process("users/password", new Context(locale, map));
        String title = templateEngine.process("users/passwordTitle", new Context(locale, map));

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setTo(email);
        helper.setSubject(title);
        helper.setText(content, true);
        helper.setFrom(javaMailSender.getUsername());

        javaMailSender.send(mimeMessage);
    } catch (MailException | MessagingException ex) {
        log.error("", ex);
        out.print("alert('?????')");
        return;
    }
    out.print("alert('???" + user.getEmail() + "??');");
}