Example usage for javax.mail.internet MimeMessage setReplyTo

List of usage examples for javax.mail.internet MimeMessage setReplyTo

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage setReplyTo.

Prototype

@Override
public void setReplyTo(Address[] addresses) throws MessagingException 

Source Link

Document

Set the RFC 822 "Reply-To" header field.

Usage

From source file:net.sourceforge.subsonic.backend.service.EmailSession.java

private MimeMessage createMessage(String from, List<String> to, List<String> cc, List<String> bcc,
        List<String> replyTo, String subject) throws MessagingException {
    MimeMessage message = new MimeMessage(session);

    message.setFrom(new InternetAddress(from));
    message.setReplyTo(new Address[] { new InternetAddress(from) });
    message.setRecipients(Message.RecipientType.TO, convertAddress(to));
    message.setRecipients(Message.RecipientType.CC, convertAddress(cc));
    message.setRecipients(Message.RecipientType.BCC, convertAddress(bcc));
    message.setReplyTo(convertAddress(replyTo));
    message.setSubject(subject);//from  w w  w . j ava  2 s.  c  o m
    return message;
}

From source file:net.sourceforge.vulcan.mailer.MessageAssembler.java

public MimeMessage constructMessage(String subscribers, ConfigDto config, ProjectStatusDto status, String html)
        throws MessagingException, AddressException {

    final MimeMessage message = new MimeMessage(mailSession);

    message.setSentDate(new Date());
    message.setFrom(new InternetAddress(config.getSenderAddress()));

    if (isNotBlank(config.getReplyToAddress())) {
        message.setReplyTo(InternetAddress.parse(config.getReplyToAddress()));
    }//  w w  w .  j a va 2s .c  o  m
    message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(subscribers));

    message.setSubject(status.getName() + ": " + status.getStatus());

    final Multipart multipart = new MimeMultipart();

    html = html.replaceAll("\\r", "");

    addMultipartBody(multipart, "text/html; charset=UTF-8", html);

    message.setContent(multipart);

    return message;
}

From source file:net.spfbl.http.ServerHTTP.java

private static boolean enviarDesbloqueio(String url, String remetente, String destinatario)
        throws SendFailedException, MessagingException {
    if (url == null) {
        return false;
    } else if (!Core.hasOutputSMTP()) {
        return false;
    } else if (!Domain.isEmail(destinatario)) {
        return false;
    } else if (NoReply.contains(destinatario, true)) {
        return false;
    } else {// www  . ja va  2 s.c  o m
        try {
            Server.logDebug("sending unblock by e-mail.");
            Locale locale = User.getLocale(destinatario);
            InternetAddress[] recipients = InternetAddress.parse(destinatario);
            Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props);
            MimeMessage message = new MimeMessage(session);
            message.setHeader("Date", Core.getEmailDate());
            message.setFrom(Core.getAdminEmail());
            message.setReplyTo(InternetAddress.parse(remetente));
            message.addRecipients(Message.RecipientType.TO, recipients);
            String subject;
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                subject = "Solicitao de envio SPFBL";
            } else {
                subject = "SPFBL send request";
            }
            message.setSubject(subject);
            // Corpo da mensagem.
            StringBuilder builder = new StringBuilder();
            builder.append("<!DOCTYPE html>\n");
            builder.append("<html lang=\"");
            builder.append(locale.getLanguage());
            builder.append("\">\n");
            builder.append("  <head>\n");
            builder.append("    <meta charset=\"UTF-8\">\n");
            builder.append("    <title>");
            builder.append(subject);
            builder.append("</title>\n");
            loadStyleCSS(builder);
            builder.append("  </head>\n");
            builder.append("  <body>\n");
            builder.append("    <div id=\"container\">\n");
            builder.append("      <div id=\"divlogo\">\n");
            builder.append("        <img src=\"cid:logo\">\n");
            builder.append("      </div>\n");
            buildMessage(builder, subject);
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder,
                        "Este e-mail foi gerado pois nosso servidor recusou uma ou mais mensagens do remetente "
                                + remetente
                                + " e o mesmo requisitou que seja feita a liberao para que novos e-mails possam ser entregues a voc.");
                buildText(builder, "Se voc deseja receber e-mails de " + remetente
                        + ", acesse o endereo abaixo e para iniciar o processo de liberao:");
            } else {
                buildText(builder,
                        "This email was generated because our server has refused one or more messages from the sender "
                                + remetente
                                + " and the same sender has requested that the release be made for new emails can be delivered to you.");
                buildText(builder, "If you wish to receive emails from " + remetente
                        + ", access the address below and to start the release process:");
            }
            buildText(builder, "<a href=\"" + url + "\">" + url + "</a>");
            buildFooter(builder, locale);
            builder.append("    </div>\n");
            builder.append("  </body>\n");
            builder.append("</html>\n");
            // Making HTML part.
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8");
            // Making logo part.
            MimeBodyPart logoPart = new MimeBodyPart();
            File logoFile = getWebFile("logo.png");
            logoPart.attachFile(logoFile);
            logoPart.setContentID("<logo>");
            logoPart.addHeader("Content-Type", "image/png");
            logoPart.setDisposition(MimeBodyPart.INLINE);
            // Join both parts.
            MimeMultipart content = new MimeMultipart("related");
            content.addBodyPart(htmlPart);
            content.addBodyPart(logoPart);
            // Set multiplart content.
            message.setContent(content);
            message.saveChanges();
            // Enviar mensagem.
            return Core.sendMessage(message, 5000);
        } catch (MailConnectException ex) {
            throw ex;
        } catch (SendFailedException ex) {
            throw ex;
        } catch (MessagingException ex) {
            throw ex;
        } catch (Exception ex) {
            Server.logError(ex);
            return false;
        }
    }
}

From source file:net.spfbl.http.ServerHTTP.java

private static boolean enviarConfirmacaoDesbloqueio(String destinatario, String remetente, Locale locale) {
    if (Core.hasOutputSMTP() && Core.hasAdminEmail() && Domain.isEmail(remetente)
            && !NoReply.contains(remetente, true)) {
        try {/*  w  w  w.  ja  v a 2s  .c om*/
            Server.logDebug("sending unblock confirmation by e-mail.");
            InternetAddress[] recipients = InternetAddress.parse(remetente);
            Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props);
            MimeMessage message = new MimeMessage(session);
            message.setHeader("Date", Core.getEmailDate());
            message.setFrom(Core.getAdminEmail());
            message.setReplyTo(InternetAddress.parse(destinatario));
            message.addRecipients(Message.RecipientType.TO, recipients);
            String subject;
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                subject = "Confirmao de desbloqueio SPFBL";
            } else {
                subject = "SPFBL unblocking confirmation";
            }
            message.setSubject(subject);
            // Corpo da mensagem.
            StringBuilder builder = new StringBuilder();
            builder.append("<!DOCTYPE html>\n");
            builder.append("<html lang=\"");
            builder.append(locale.getLanguage());
            builder.append("\">\n");
            builder.append("  <head>\n");
            builder.append("    <meta charset=\"UTF-8\">\n");
            builder.append("    <title>");
            builder.append(subject);
            builder.append("</title>\n");
            loadStyleCSS(builder);
            builder.append("  </head>\n");
            builder.append("  <body>\n");
            builder.append("    <div id=\"container\">\n");
            builder.append("      <div id=\"divlogo\">\n");
            builder.append("        <img src=\"cid:logo\">\n");
            builder.append("      </div>\n");
            buildMessage(builder, subject);
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildText(builder, "O destinatrio '" + destinatario
                        + "' acabou de liberar o recebimento de suas mensagens.");
                buildText(builder, "Por favor, envie novamente a mensagem anterior.");
            } else {
                buildText(builder,
                        "The recipient '" + destinatario + "' just released the receipt of your message.");
                buildText(builder, "Please send the previous message again.");
            }
            buildFooter(builder, locale);
            builder.append("    </div>\n");
            builder.append("  </body>\n");
            builder.append("</html>\n");
            // Making HTML part.
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8");
            // Making logo part.
            MimeBodyPart logoPart = new MimeBodyPart();
            File logoFile = getWebFile("logo.png");
            logoPart.attachFile(logoFile);
            logoPart.setContentID("<logo>");
            logoPart.addHeader("Content-Type", "image/png");
            logoPart.setDisposition(MimeBodyPart.INLINE);
            // Join both parts.
            MimeMultipart content = new MimeMultipart("related");
            content.addBodyPart(htmlPart);
            content.addBodyPart(logoPart);
            // Set multiplart content.
            message.setContent(content);
            message.saveChanges();
            // Enviar mensagem.
            return Core.sendMessage(message, 5000);
        } catch (MessagingException ex) {
            return false;
        } catch (Exception ex) {
            Server.logError(ex);
            return false;
        }
    } else {
        return false;
    }
}

From source file:nz.co.testamation.common.mail.MimeMessageFactoryImpl.java

@Override
public Message create(Email email) {
    try {//  w  w  w.j  ava 2s.c  om
        EmailAddresses emailAddresses = email.getEmailAddresses();

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSubject(email.getSubject());
        mimeMessage.setFrom(new InternetAddress(emailAddresses.getFrom()));

        if (StringUtils.isNotBlank(emailAddresses.getReplyTo())) {
            mimeMessage.setReplyTo(InternetAddress.parse(emailAddresses.getReplyTo()));
        }

        addRecipients(mimeMessage, Message.RecipientType.TO, emailAddresses.getToAddresses());
        addRecipients(mimeMessage, Message.RecipientType.CC, emailAddresses.getCcAddresses());
        addRecipients(mimeMessage, Message.RecipientType.BCC, emailAddresses.getBccAddresses());

        mimeMessage.setContent(multipartMessageFactory.create(email));
        mimeMessage.setSentDate(new Date());

        return mimeMessage;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:org.asqatasun.emailsender.EmailSender.java

/**
 *
 * @param emailFrom//from  www  .j  a v  a  2s . c o  m
 * @param emailToSet
 * @param emailBccSet (can be null)
 * @param replyTo (can be null)
 * @param emailSubject
 * @param emailContent
 */
public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo,
        String emailSubject, String emailContent) {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // create some properties and get the default Session
    Session session = Session.getInstance(props);
    session.setDebug(debug);
    try {
        Transport t = session.getTransport("smtp");
        t.connect(smtpHost, userName, password);

        // create a message
        MimeMessage msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom;
        try {
            // Used default from address is passed one is null or empty or
            // blank
            addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom)
                    : new InternetAddress(from);
            msg.setFrom(addressFrom);
            Address[] recipients = new InternetAddress[emailToSet.size()];
            int i = 0;
            for (String emailTo : emailToSet) {
                recipients[i] = new InternetAddress(emailTo);
                i++;
            }

            msg.setRecipients(Message.RecipientType.TO, recipients);

            if (CollectionUtils.isNotEmpty(emailBccSet)) {
                Address[] bccRecipients = new InternetAddress[emailBccSet.size()];
                i = 0;
                for (String emailBcc : emailBccSet) {
                    bccRecipients[i] = new InternetAddress(emailBcc);
                    i++;
                }
                msg.setRecipients(Message.RecipientType.BCC, bccRecipients);
            }

            if (StringUtils.isNotBlank(replyTo)) {
                Address[] replyToRecipients = { new InternetAddress(replyTo) };
                msg.setReplyTo(replyToRecipients);
            }

            // Setting the Subject
            msg.setSubject(emailSubject, CHARSET_KEY);

            // Setting content and charset (warning: both declarations of
            // charset are needed)
            msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY);
            LOGGER.debug("emailContent  " + emailContent);
            msg.setContent(emailContent, FULL_CHARSET_KEY);
            try {
                LOGGER.debug("emailContent from message object " + msg.getContent().toString());
            } catch (IOException ex) {
                LOGGER.error(ex.getMessage());
            } catch (MessagingException ex) {
                LOGGER.error(ex.getMessage());
            }
            for (Address addr : msg.getAllRecipients()) {
                LOGGER.debug("addr " + addr);
            }
            t.sendMessage(msg, msg.getAllRecipients());
        } catch (AddressException ex) {
            LOGGER.warn("AddressException " + ex.getMessage());
            LOGGER.warn("AddressException " + ex.getStackTrace());
        }
    } catch (NoSuchProviderException e) {
        LOGGER.warn("NoSuchProviderException " + e.getMessage());
        LOGGER.warn("NoSuchProviderException " + e.getStackTrace());
    } catch (MessagingException e) {
        LOGGER.warn("MessagingException " + e.getMessage());
        LOGGER.warn("MessagingException " + e.getStackTrace());
    }
}

From source file:org.eclipse.che.mail.MailSender.java

public void sendMail(EmailBean emailBean) throws SendMailException {
    File tempDir = null;//from  w w  w  . j  a v  a 2  s.  c  om
    try {
        MimeMessage message = new MimeMessage(mailSessionProvider.get());
        Multipart contentPart = new MimeMultipart();

        MimeBodyPart bodyPart = new MimeBodyPart();
        bodyPart.setText(emailBean.getBody(), "UTF-8", getSubType(emailBean.getMimeType()));
        contentPart.addBodyPart(bodyPart);

        if (emailBean.getAttachments() != null) {
            tempDir = Files.createTempDir();
            for (Attachment attachment : emailBean.getAttachments()) {
                // Create attachment file in temporary directory
                byte[] attachmentContent = Base64.getDecoder().decode(attachment.getContent());
                File attachmentFile = new File(tempDir, attachment.getFileName());
                Files.write(attachmentContent, attachmentFile);

                // Attach the attachment file to email
                MimeBodyPart attachmentPart = new MimeBodyPart();
                attachmentPart.attachFile(attachmentFile);
                attachmentPart.setContentID("<" + attachment.getContentId() + ">");
                contentPart.addBodyPart(attachmentPart);
            }
        }

        message.setContent(contentPart);
        message.setSubject(emailBean.getSubject(), "UTF-8");
        message.setFrom(new InternetAddress(emailBean.getFrom(), true));
        message.setSentDate(new Date());
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailBean.getTo()));

        if (emailBean.getReplyTo() != null) {
            message.setReplyTo(InternetAddress.parse(emailBean.getReplyTo()));
        }
        LOG.info("Sending from {} to {} with subject {}", emailBean.getFrom(), emailBean.getTo(),
                emailBean.getSubject());

        Transport.send(message);
        LOG.debug("Mail sent");
    } catch (Exception e) {
        LOG.error(e.getLocalizedMessage());
        throw new SendMailException(e.getLocalizedMessage(), e);
    } finally {
        if (tempDir != null) {
            try {
                FileUtils.deleteDirectory(tempDir);
            } catch (IOException exception) {
                LOG.error(exception.getMessage());
            }
        }
    }
}

From source file:org.exist.xquery.modules.mail.SendEmailFunction.java

/**
 * Constructs a mail Object from an XML representation of an email
 *
 * The XML email Representation is expected to look something like this
 *
 * <mail>//from  w w w .  java 2  s .  co m
 *    <from></from>
 *    <reply-to></reply-to>
 *    <to></to>
 *    <cc></cc>
 *    <bcc></bcc>
 *    <subject></subject>
 *    <message>
 *       <text charset="" encoding=""></text>
 *       <xhtml charset="" encoding=""></xhtml>
 *       <generic charset="" type="" encoding=""></generic>
 *    </message>
 *    <attachment mimetype="" filename=""></attachment>
 * </mail>
 *
 * @param mailElements   The XML mail Node
 * @return      A mail Object representing the XML mail Node
 */
private List<Message> parseMessageElement(Session session, List<Element> mailElements)
        throws IOException, MessagingException, TransformerException {
    List<Message> mails = new ArrayList<>();

    for (Element mailElement : mailElements) {
        //Make sure that message has a Mail node
        if (mailElement.getLocalName().equals("mail")) {
            //New message Object
            // create a message
            MimeMessage msg = new MimeMessage(session);

            ArrayList<InternetAddress> replyTo = new ArrayList<>();
            boolean fromWasSet = false;
            MimeBodyPart body = null;
            Multipart multibody = null;
            ArrayList<MimeBodyPart> attachments = new ArrayList<>();
            String firstContent = null;
            String firstContentType = null;
            String firstCharset = null;
            String firstEncoding = null;

            //Get the First Child
            Node child = mailElement.getFirstChild();
            while (child != null) {
                //Parse each of the child nodes
                if (child.getNodeType() == Node.ELEMENT_NODE && child.hasChildNodes()) {
                    switch (child.getLocalName()) {
                    case "from":
                        // set the from and to address
                        InternetAddress[] addressFrom = {
                                new InternetAddress(child.getFirstChild().getNodeValue()) };
                        msg.addFrom(addressFrom);
                        fromWasSet = true;
                        break;
                    case "reply-to":
                        // As we can only set the reply-to, not add them, let's keep
                        // all of them in a list
                        replyTo.add(new InternetAddress(child.getFirstChild().getNodeValue()));
                        msg.setReplyTo(replyTo.toArray(new InternetAddress[0]));
                        break;
                    case "to":
                        msg.addRecipient(Message.RecipientType.TO,
                                new InternetAddress(child.getFirstChild().getNodeValue()));
                        break;
                    case "cc":
                        msg.addRecipient(Message.RecipientType.CC,
                                new InternetAddress(child.getFirstChild().getNodeValue()));
                        break;
                    case "bcc":
                        msg.addRecipient(Message.RecipientType.BCC,
                                new InternetAddress(child.getFirstChild().getNodeValue()));
                        break;
                    case "subject":
                        msg.setSubject(child.getFirstChild().getNodeValue());
                        break;
                    case "header":
                        // Optional : You can also set your custom headers in the Email if you Want
                        msg.addHeader(((Element) child).getAttribute("name"),
                                child.getFirstChild().getNodeValue());
                        break;
                    case "message":
                        //If the message node, then parse the child text and xhtml nodes
                        Node bodyPart = child.getFirstChild();
                        while (bodyPart != null) {
                            if (bodyPart.getNodeType() != Node.ELEMENT_NODE)
                                continue;

                            Element elementBodyPart = (Element) bodyPart;
                            String content = null;
                            String contentType = null;

                            if (bodyPart.getLocalName().equals("text")) {
                                // Setting the Subject and Content Type
                                content = bodyPart.getFirstChild().getNodeValue();
                                contentType = "plain";
                            } else if (bodyPart.getLocalName().equals("xhtml")) {
                                //Convert everything inside <xhtml></xhtml> to text
                                TransformerFactory transFactory = TransformerFactory.newInstance();
                                Transformer transformer = transFactory.newTransformer();
                                DOMSource source = new DOMSource(bodyPart.getFirstChild());
                                StringWriter strWriter = new StringWriter();
                                StreamResult result = new StreamResult(strWriter);
                                transformer.transform(source, result);

                                content = strWriter.toString();
                                contentType = "html";
                            } else if (bodyPart.getLocalName().equals("generic")) {
                                // Setting the Subject and Content Type
                                content = elementBodyPart.getFirstChild().getNodeValue();
                                contentType = elementBodyPart.getAttribute("type");
                            }

                            // Now, time to store it
                            if (content != null && contentType != null && contentType.length() > 0) {
                                String charset = elementBodyPart.getAttribute("charset");
                                String encoding = elementBodyPart.getAttribute("encoding");

                                if (body != null && multibody == null) {
                                    multibody = new MimeMultipart("alternative");
                                    multibody.addBodyPart(body);
                                }

                                if (StringUtils.isEmpty(charset)) {
                                    charset = "UTF-8";
                                }

                                if (StringUtils.isEmpty(encoding)) {
                                    encoding = "quoted-printable";
                                }

                                if (body == null) {
                                    firstContent = content;
                                    firstCharset = charset;
                                    firstContentType = contentType;
                                    firstEncoding = encoding;
                                }
                                body = new MimeBodyPart();
                                body.setText(content, charset, contentType);
                                if (encoding != null) {
                                    body.setHeader("Content-Transfer-Encoding", encoding);
                                }
                                if (multibody != null)
                                    multibody.addBodyPart(body);
                            }

                            //next body part
                            bodyPart = bodyPart.getNextSibling();
                        }
                        break;
                    case "attachment":
                        Element attachment = (Element) child;
                        MimeBodyPart part;
                        // if mimetype indicates a binary resource, assume the content is base64 encoded
                        if (MimeTable.getInstance().isTextContent(attachment.getAttribute("mimetype"))) {
                            part = new MimeBodyPart();
                        } else {
                            part = new PreencodedMimeBodyPart("base64");
                        }
                        StringBuilder content = new StringBuilder();
                        Node attachChild = attachment.getFirstChild();
                        while (attachChild != null) {
                            if (attachChild.getNodeType() == Node.ELEMENT_NODE) {
                                TransformerFactory transFactory = TransformerFactory.newInstance();
                                Transformer transformer = transFactory.newTransformer();
                                DOMSource source = new DOMSource(attachChild);
                                StringWriter strWriter = new StringWriter();
                                StreamResult result = new StreamResult(strWriter);
                                transformer.transform(source, result);

                                content.append(strWriter.toString());
                            } else {
                                content.append(attachChild.getNodeValue());
                            }
                            attachChild = attachChild.getNextSibling();
                        }
                        part.setDataHandler(new DataHandler(new ByteArrayDataSource(content.toString(),
                                attachment.getAttribute("mimetype"))));
                        part.setFileName(attachment.getAttribute("filename"));
                        //                            part.setHeader("Content-Transfer-Encoding", "base64");
                        attachments.add(part);
                        break;
                    }
                }

                //next node
                child = child.getNextSibling();

            }
            // Lost from
            if (!fromWasSet)
                msg.setFrom();

            // Preparing content and attachments
            if (attachments.size() > 0) {
                if (multibody == null) {
                    multibody = new MimeMultipart("mixed");
                    if (body != null) {
                        multibody.addBodyPart(body);
                    }
                } else {
                    MimeMultipart container = new MimeMultipart("mixed");
                    MimeBodyPart containerBody = new MimeBodyPart();
                    containerBody.setContent(multibody);
                    container.addBodyPart(containerBody);
                    multibody = container;
                }
                for (MimeBodyPart part : attachments) {
                    multibody.addBodyPart(part);
                }
            }

            // And now setting-up content
            if (multibody != null) {
                msg.setContent(multibody);
            } else if (body != null) {
                msg.setText(firstContent, firstCharset, firstContentType);
                if (firstEncoding != null) {
                    msg.setHeader("Content-Transfer-Encoding", firstEncoding);
                }
            }

            msg.saveChanges();
            mails.add(msg);
        }
    }

    return mails;
}

From source file:org.georchestra.console.ws.emails.EmailController.java

/**
 * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist.
 *
 * Json sent should have following keys :
 *
 * - to      : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"]
 * - cc      : json array of email to 'CC' email ex: ["him@rm.fr"]
 * - bcc     : json array of email to add recipient as blind CC ["secret@rm.fr"]
 * - subject : subject of email//from w  w  w  . j  av a  2s . co  m
 * - body    : Body of email
 *
 * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory.
 *
 * complete json example :
 *
 * {
 *   "to": ["you@rm.fr", "another-guy@rm.fr"],
 *   "cc": ["him@rm.fr"],
 *   "bcc": ["secret@rm.fr"],
 *   "subject": "test email",
 *   "body": "Hi, this a test EMail, please do not reply."
 * }
 *
 */
@RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json")
@ResponseBody
public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request)
        throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException {

    JSONObject payload = new JSONObject(rawRequest);
    InternetAddress[] to = this.populateRecipient("to", payload);
    InternetAddress[] cc = this.populateRecipient("cc", payload);
    InternetAddress[] bcc = this.populateRecipient("bcc", payload);

    this.checkSubject(payload);
    this.checkBody(payload);
    this.checkRecipient(to, cc, bcc);

    LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to="
            + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc="
            + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles"));

    LOG.debug("EMail request : " + payload.toString());

    // Instanciate MimeMessage
    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost());
    session.getProperties().setProperty("mail.smtp.port",
            (new Integer(this.emailFactory.getSmtpPort())).toString());
    MimeMessage message = new MimeMessage(session);

    // Generate From header
    InternetAddress from = new InternetAddress();
    from.setAddress(this.georConfig.getProperty("emailProxyFromAddress"));
    from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setFrom(from);

    // Generate Reply-to header
    InternetAddress replyTo = new InternetAddress();
    replyTo.setAddress(request.getHeader("sec-email"));
    replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setReplyTo(new Address[] { replyTo });

    // Generate to, cc and bcc headers
    if (to.length > 0)
        message.setRecipients(Message.RecipientType.TO, to);
    if (cc.length > 0)
        message.setRecipients(Message.RecipientType.CC, cc);
    if (bcc.length > 0)
        message.setRecipients(Message.RecipientType.BCC, bcc);

    // Add subject and body
    message.setSubject(payload.getString("subject"), "UTF-8");
    message.setText(payload.getString("body"), "UTF-8", "plain");
    message.setSentDate(new Date());

    // finally send message
    Transport.send(message);

    JSONObject res = new JSONObject();
    res.put("success", true);
    return res.toString();
}

From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java

/**
 * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist.
 *
 * Json sent should have following keys :
 *
 * - to      : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"]
 * - cc      : json array of email to 'CC' email ex: ["him@rm.fr"]
 * - bcc     : json array of email to add recipient as blind CC ["secret@rm.fr"]
 * - subject : subject of email//from w w  w . j av a 2s.c  om
 * - body    : Body of email
 *
 * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory.
 *
 * complete json example :
 *
 * {
 *   "to": ["you@rm.fr", "another-guy@rm.fr"],
 *   "cc": ["him@rm.fr"],
 *   "bcc": ["secret@rm.fr"],
 *   "subject": "test email",
 *   "body": "Hi, this a test EMail, please do not reply."
 * }
 *
 */
@RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json")
@ResponseBody
public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request)
        throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException {

    JSONObject payload = new JSONObject(rawRequest);
    InternetAddress[] to = this.populateRecipient("to", payload);
    InternetAddress[] cc = this.populateRecipient("cc", payload);
    InternetAddress[] bcc = this.populateRecipient("bcc", payload);

    this.checkSubject(payload);
    this.checkBody(payload);
    this.checkRecipient(to, cc, bcc);

    LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to="
            + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc="
            + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles"));

    LOG.debug("EMail request : " + payload.toString());

    // Instanciate MimeMessage
    Properties props = System.getProperties();
    props.put("mail.smtp.host", this.emailFactory.getSmtpHost());
    props.put("mail.protocol.port", this.emailFactory.getSmtpPort());
    Session session = Session.getInstance(props, null);
    MimeMessage message = new MimeMessage(session);

    // Generate From header
    InternetAddress from = new InternetAddress();
    from.setAddress(this.georConfig.getProperty("emailProxyFromAddress"));
    from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setFrom(from);

    // Generate Reply-to header
    InternetAddress replyTo = new InternetAddress();
    replyTo.setAddress(request.getHeader("sec-email"));
    replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setReplyTo(new Address[] { replyTo });

    // Generate to, cc and bcc headers
    if (to.length > 0)
        message.setRecipients(Message.RecipientType.TO, to);
    if (cc.length > 0)
        message.setRecipients(Message.RecipientType.CC, cc);
    if (bcc.length > 0)
        message.setRecipients(Message.RecipientType.BCC, bcc);

    // Add subject and body
    message.setSubject(payload.getString("subject"), "UTF-8");
    message.setText(payload.getString("body"), "UTF-8", "plain");
    message.setSentDate(new Date());

    // finally send message
    Transport.send(message);

    JSONObject res = new JSONObject();
    res.put("success", true);
    return res.toString();
}