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, String personal) throws MessagingException, UnsupportedEncodingException 

Source Link

Usage

From source file:dao.Mailer.java

public void send(String from, String to, String subject, String body) {
    try {/*from www.  j a v a  2  s. c o  m*/
        MimeMessage mail = mailer.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mail, true);
        helper.setFrom(from, from);
        helper.setTo(to);
        helper.setReplyTo(from, from);
        helper.setSubject(subject);
        helper.setText(body, true);
        helper.setSentDate(new Date());

        mailer.send(mail);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:controller.MailerController.java

@RequestMapping("send")
public String send(ModelMap model, @RequestParam("from") String from, @RequestParam("to") String to,
        @RequestParam("subject") String subject, @RequestParam("body") String body) {
    try {// www. j a v a  2  s.  c om
        //To mail
        MimeMessage mail = mailer.createMimeMessage();
        // S dng lp h tr
        MimeMessageHelper helper = new MimeMessageHelper(mail);
        helper.setFrom(from, from);
        helper.setTo(to);
        helper.setReplyTo(from, from);
        helper.setSubject(subject);
        helper.setText(body, true);
        //Gi mail
        mailer.send(mail);
        model.addAttribute("message", "Send mail succes");
    } catch (Exception e) {
        model.addAttribute("message", "Send mail fail");
    }
    return "admin/mail";
}

From source file:com.baomidou.framework.mail.MailHelper.java

/**
 * ??/*from  w ww  .  java 2 s .c o m*/
 * 
 * @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;
}

From source file:com.exp.tracker.utils.EmailUtility.java

/**
 * Sends an email./*from ww w.  j av  a2s. c o  m*/
 * 
 * @param emailIdStrings
 *            A String array containing a list of email addresses.
 * @param emailSubject
 *            The subject of the email.
 * @param messageContent
 *            The message body.
 * @param emailAttachments
 *            A map containing any attachments. The key should be the file
 *            name. The value os a byte[] containing the binary
 *            representation of the attachment.
 * @throws EmailCommunicationException
 *             If any exception occurs.
 */
public void sendEmail(String[] emailIdStrings, String emailSubject, String messageContent,
        Map<String, byte[]> emailAttachments) throws EmailCommunicationException {
    if (null == emailIdStrings) {
        throw new EmailCommunicationException("Null array passed to this method.");
    }
    if (emailIdStrings.length == 0) {
        throw new EmailCommunicationException("No email addresses were provided. Array was empty.");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("About to send an email.");
    }

    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        helper.setFrom(fromAccount, fromName);
        InternetAddress[] toListArray = new InternetAddress[emailIdStrings.length];
        for (int i = 0; i < emailIdStrings.length; i++) {
            toListArray[i] = new InternetAddress(emailIdStrings[i]);
        }
        //To
        helper.setTo(toListArray);
        //Subject
        helper.setSubject(emailSubject);
        //Body
        helper.setText(messageContent, true);
        //Attachments
        if (null != emailAttachments) {
            Set<String> attachmentFileNames = emailAttachments.keySet();
            for (String fileName : attachmentFileNames) {
                helper.addAttachment(fileName,
                        new ByteArrayDataSource(emailAttachments.get(fileName), "application/octet-stream"));
            }
        }

        javaMailSender.send(mimeMessage);
        System.out.println("Mail sent successfully.");
    } catch (MessagingException e) {
        throw new EmailCommunicationException("Error sending email.", e);
    } catch (UnsupportedEncodingException e) {
        throw new EmailCommunicationException("Error sending email. Unsupported encoding.", e);
    }
}

From source file:com.enonic.cms.core.mail.AbstractSendMailService.java

private MimeMessageHelper createMessage(MessageSettings settings, boolean multipart) throws Exception {
    final MimeMessageHelper message = new MimeMessageHelper(this.mailSender.createMimeMessage(), multipart,
            MAIL_ENCODING);/*from w  w w.  j  av  a  2  s  .  c  o m*/
    message.setFrom(settings.getFromMail(), settings.getFromName());
    return message;
}

From source file:app.service.CaptchaService.java

protected void sendEmail(String email, String authCode)
        throws MessagingException, UnsupportedEncodingException {
    MimeMessage mimeMessage = mMailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "UTF-8");
    helper.setSubject(" LsPush ");
    helper.setFrom(serverEmail, serverName);
    helper.setTo(email);/*from  w  w  w  .ja  v  a2 s . co  m*/

    String authLink = String.format("%s/user/auth?auth_code=%s", serverUrl, authCode);
    final Context ctx = new Context(Locale.CHINA);
    ctx.setVariable("serverUrl", serverUrl);
    ctx.setVariable("serverName", serverName);
    ctx.setVariable("email", email);
    ctx.setVariable("authCode", authCode);
    ctx.setVariable("authLink", authLink);

    String html = mTemplateEngine.process("lspush_captcha_email", ctx);

    helper.setText(html, true);
    mMailSender.send(mimeMessage);
}

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 {//ww w  . j  a v  a 2 s . c  om
        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.beanfuse.notification.mail.AbstractMailNotifier.java

public void sendMessage(Message msg) throws NotificationException {
    // contruct a MailMessage
    MailMessage mailConext = null;/* w  w w. j  a  va2  s. c o m*/
    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:alfio.manager.system.SmtpMailer.java

@Override
public void send(Event event, String to, List<String> cc, String subject, String text, Optional<String> html,
        Attachment... attachments) {/*from   w  ww  . java  2  s .  co m*/
    MimeMessagePreparator preparator = (mimeMessage) -> {
        MimeMessageHelper message = html.isPresent() || !ArrayUtils.isEmpty(attachments)
                ? new MimeMessageHelper(mimeMessage, true, "UTF-8")
                : new MimeMessageHelper(mimeMessage, "UTF-8");
        message.setSubject(subject);
        message.setFrom(
                configurationManager.getRequiredValue(
                        Configuration.from(event.getOrganizationId(), event.getId(), SMTP_FROM_EMAIL)),
                event.getDisplayName());
        String replyTo = configurationManager.getStringConfigValue(
                Configuration.from(event.getOrganizationId(), event.getId(), MAIL_REPLY_TO), "");
        if (StringUtils.isNotBlank(replyTo)) {
            message.setReplyTo(replyTo);
        }
        message.setTo(to);
        if (cc != null && !cc.isEmpty()) {
            message.setCc(cc.toArray(new String[cc.size()]));
        }
        if (html.isPresent()) {
            message.setText(text, html.get());
        } else {
            message.setText(text, false);
        }

        if (attachments != null) {
            for (Attachment a : attachments) {
                message.addAttachment(a.getFilename(), new ByteArrayResource(a.getSource()),
                        a.getContentType());
            }
        }

        message.getMimeMessage().saveChanges();
        message.getMimeMessage().removeHeader("Message-ID");
    };
    toMailSender(event).send(preparator);
}

From source file:business.services.MailService.java

@Transactional
public void sendAgreementFormLink(@NotNull String email, @NotNull RequestProperties request) {
    log.info("Send agreement form link for request " + request.getRequestNumber() + ".");

    log.info("Sending link to " + email);
    try {/*from w w  w .  j a va  2s .  c  om*/
        MimeMessageHelper message = new MimeMessageHelper(mailSender.createMimeMessage());
        message.setTo(email);
        message.setFrom(getFrom(), fromName);
        message.setReplyTo(replyAddress, replyName);
        message.setSubject(String.format("Nieuwe PALGA-aanvraag ontvangen, aanvraagnummer: %s",
                request.getRequestNumber()));
        String agreementFormLink = getLink("/#/request/" + request.getProcessInstanceId() + "/agreementform");
        message.setText(String.format(requesterAgreementFormLinkTemplate, agreementFormLink));
        mailSender.send(message.getMimeMessage());
    } catch (MessagingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    }
}