Example usage for javax.mail Message setContent

List of usage examples for javax.mail Message setContent

Introduction

In this page you can find the example usage for javax.mail Message setContent.

Prototype

public void setContent(Object obj, String type) throws MessagingException;

Source Link

Document

A convenience method for setting this part's content.

Usage

From source file:com.app.mail.DefaultMailSender.java

private Message _populateEmailMessage(Map<SearchQuery, List<SearchResult>> searchQueryResultMap,
        String recipientEmailAddress, String unsubscribeToken, Session session) throws Exception {

    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(PropertiesValues.OUTBOUND_EMAIL_ADDRESS, "Auction Alert"));

    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmailAddress));

    message.setSubject("New Search Results - " + MailUtil.getCurrentDate());

    Map<String, Object> rootMap = new HashMap<>();

    rootMap.put("emailAddress", recipientEmailAddress);
    rootMap.put("searchQueryResultMap", searchQueryResultMap);
    rootMap.put("unsubscribeToken", MailUtil.escapeUnsubscribeToken(unsubscribeToken));
    rootMap.put("numberTool", new NumberTool());
    rootMap.put("rootDomainName", PropertiesValues.ROOT_DOMAIN_NAME);

    String messageBody = VelocityEngineUtils.mergeTemplateIntoString(_velocityEngine, "template/email_body.vm",
            "UTF-8", rootMap);

    message.setContent(messageBody, "text/html");

    return message;
}

From source file:com.enonic.vertical.userservices.OrderHandlerController.java

private void sendMail(String receiverEmail, String receiverName, String senderEmail, String senderName,
        String subject, String message) throws MessagingException, UnsupportedEncodingException {

    // smtp server
    Properties smtpProperties = new Properties();
    smtpProperties.put("mail.smtp.host", verticalProperties.getMailSmtpHost());
    Session session = Session.getDefaultInstance(smtpProperties, null);

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

    // set from address
    if (senderEmail != null && !senderEmail.equals("")) {
        InternetAddress addressFrom = new InternetAddress(senderEmail);
        if (senderName != null && !senderName.equals("")) {
            addressFrom.setPersonal(senderName);
        }/*www.j  ava 2  s.  c om*/
        msg.setFrom(addressFrom);
    }

    // set to address
    InternetAddress addressTo = new InternetAddress(receiverEmail);
    if (receiverName != null) {
        addressTo.setPersonal(receiverName);
    }
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    // Setting subject and content type
    msg.setSubject(subject);

    message = RegexpUtil.substituteAll("(\\\\n)", "\n", message);
    msg.setContent(message, "text/plain; charset=UTF-8");

    // send message
    Transport.send(msg);
}

From source file:dk.netarkivet.common.utils.EMailUtils.java

/**
 * Send an email, possibly forgiving errors.
 *
 * @param to The recipient of the email. Separate multiple recipients with
 *           commas. Supports only adresses of the type 'john@doe.dk', not
 *           'John Doe <john@doe.dk>'
 * @param from The sender of the email.//from w ww  . j ava2 s.c  om
 * @param subject The subject of the email.
 * @param body The body of the email.
 * @param forgive On true, will send the email even on invalid email
 *        addresses, if at least one recipient can be set, on false, will
 *        throw exceptions on any invalid email address.
 *
 *
 * @throws ArgumentNotValid If either parameter is null, if to, from or
 *                          subject is the empty string, or no recipient
 *                          can be set. If "forgive" is false, also on
 *                          any invalid to or from address.
 * @throws IOFailure If the message cannot be sent for some reason.
 */
public static void sendEmail(String to, String from, String subject, String body, boolean forgive) {
    ArgumentNotValid.checkNotNullOrEmpty(to, "String to");
    ArgumentNotValid.checkNotNullOrEmpty(from, "String from");
    ArgumentNotValid.checkNotNullOrEmpty(subject, "String subject");
    ArgumentNotValid.checkNotNull(body, "String body");

    Properties props = new Properties();
    props.put(MAIL_FROM_PROPERTY_KEY, from);
    props.put(MAIL_HOST_PROPERTY_KEY, Settings.get(CommonSettings.MAIL_SERVER));

    Session session = Session.getDefaultInstance(props);
    Message msg = new MimeMessage(session);

    // to might contain more than one e-mail address
    for (String toAddressS : to.split(",")) {
        try {
            InternetAddress toAddress = new InternetAddress(toAddressS.trim());
            msg.addRecipient(Message.RecipientType.TO, toAddress);
        } catch (AddressException e) {
            if (forgive) {
                log.warn("To address '" + toAddressS + "' is not a valid email " + "address", e);
            } else {
                throw new ArgumentNotValid("To address '" + toAddressS + "' is not a valid email " + "address",
                        e);
            }
        } catch (MessagingException e) {
            if (forgive) {
                log.warn("To address '" + toAddressS + "' could not be set in email", e);
            } else {
                throw new ArgumentNotValid("To address '" + toAddressS + "' could not be set in email", e);
            }
        }
    }
    try {
        if (msg.getAllRecipients().length == 0) {
            throw new ArgumentNotValid("No valid recipients in '" + to + "'");
        }
    } catch (MessagingException e) {
        throw new ArgumentNotValid("Message invalid after setting" + " recipients", e);
    }

    try {
        InternetAddress fromAddress = null;
        fromAddress = new InternetAddress(from);
        msg.setFrom(fromAddress);
    } catch (AddressException e) {
        throw new ArgumentNotValid("From address '" + from + "' is not a valid email " + "address", e);
    } catch (MessagingException e) {
        if (forgive) {
            log.warn("From address '" + from + "' could not be set in email", e);
        } else {
            throw new ArgumentNotValid("From address '" + from + "' could not be set in email", e);
        }
    }

    try {
        msg.setSubject(subject);
        msg.setContent(body, MIMETYPE);
        msg.setSentDate(new Date());
        Transport.send(msg);
    } catch (MessagingException e) {
        throw new IOFailure("Could not send email with subject '" + subject + "' from '" + from + "' to '" + to
                + "'. Body:\n" + body, e);
    }
}

From source file:org.springfield.lou.application.types.EuscreenxlitemApplication.java

public void sendContentProviderMail(Screen s, String data) {
    //System.out.println("Send mail to CP: " + data);

    JSONObject form = (JSONObject) JSONValue.parse(data);

    String mailfrom = "euscreen-portal@noterik.nl";
    String mailsubject = "Somebody showed interest in your item on EUScreen";
    String email = (String) form.get("email");
    String id = (String) form.get("identifier");
    String provider = (String) form.get("provider");
    String subject = (String) form.get("subject");
    String title = (String) form.get("title");
    String message = (String) form.get("message");
    message = message.replaceAll("(\r\n|\n)", "<br />");

    //Form validation
    JSONObject mailResponse = new JSONObject();
    Set<String> keys = form.keySet();
    boolean errors = false;
    for (String key : keys) {
        String value = (String) form.get(key);
        if (value == null || value.isEmpty()) {
            errors = true;//from   www  .  j  a v  a2  s. c o  m
            break;
        }
    }

    if (errors) {
        mailResponse.put("status", "false");
        mailResponse.put("message", "Please fill in all the fields.");
        s.putMsg("copyright", "", "showMailResponse(" + mailResponse + ")");
        return;
    }

    String toemail = null;
    //Find the provider email
    FsNode providerNode = Fs.getNode("/domain/euscreenxl/user/" + provider + "/account/default");
    toemail = providerNode.getProperty("email");

    String body = "Identifier: " + id + "<br/>";
    body += "Title: " + title + "<br/>";
    body += "Link to item on EUScreen:<br/>";
    body += "<a href=\"http://euscreen.eu/item.html?id=" + id + "\">http://euscreen.eu/item.html?id=" + id
            + "</a><br/>";
    body += "-------------------------------------------<br/><br/>";
    body += "Subject: " + subject + "<br/>";
    body += "Message:<br/>";
    body += message + "<br/><br/>";
    body += "-------------------------------------------<br/>";
    body += "You can contact the sender of this message on: <a href=\"mailto:" + email + "\">" + email
            + "</a><br/>";

    if (this.inDevelMode()) { //In devel mode always send the email to the one filled in the form
        toemail = email;
    }

    //!!! Hack to send the email to the one filled in the form (for testing purposes). When on production it should be removed
    //toemail = email;

    boolean success = true;
    if (toemail != null) {
        try {
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            Session session = (Session) envCtx.lookup("mail/Session");

            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(mailfrom));
            InternetAddress to[] = new InternetAddress[1];
            to[0] = new InternetAddress(toemail);
            msg.setRecipients(Message.RecipientType.TO, to);

            InternetAddress bcc[] = new InternetAddress[1];
            bcc[0] = new InternetAddress("r.rozendal@noterik.nl");
            msg.setRecipients(Message.RecipientType.BCC, bcc);

            msg.setSubject(mailsubject);
            msg.setContent(body, "text/html");
            Transport.send(msg);
        } catch (Exception e) {
            System.out.println("Failed sending email: " + e);
            success = false;
        }
    } else {
        success = false;
    }

    String response = "Your message has been successfuly sent.";
    if (!success)
        response = "There was a problem sending your mail.<br/>Please try again later.";

    mailResponse.put("status", Boolean.toString(success));
    mailResponse.put("message", response);

    s.putMsg("copyright", "", "showMailResponse(" + mailResponse + ")");

}

From source file:contestWebsite.ContactUs.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Query query = new Query("user")
            .setFilter(new FilterPredicate("name", FilterOperator.EQUAL, req.getParameter("name")));
    List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(3));
    Entity feedback = new Entity("feedback");
    if (users.size() != 0) {
        feedback.setProperty("user-id", users.get(0).getProperty("user-id"));
    }//w w  w . j  av  a 2s.com

    String name = escapeHtml4(req.getParameter("name"));
    String school = escapeHtml4(req.getParameter("school"));
    String comment = escapeHtml4(req.getParameter("text"));
    String email = escapeHtml4(req.getParameter("email"));

    HttpSession sess = req.getSession(true);
    sess.setAttribute("name", name);
    sess.setAttribute("school", school);
    sess.setAttribute("email", email);
    sess.setAttribute("comment", comment);

    Entity contestInfo = Retrieve.contestInfo();
    if (!(Boolean) sess.getAttribute("nocaptcha")) {
        URL reCaptchaURL = new URL("https://www.google.com/recaptcha/api/siteverify");
        String charset = java.nio.charset.StandardCharsets.UTF_8.name();
        String reCaptchaQuery = String.format("secret=%s&response=%s&remoteip=%s",
                URLEncoder.encode((String) contestInfo.getProperty("privateKey"), charset),
                URLEncoder.encode(req.getParameter("g-recaptcha-response"), charset),
                URLEncoder.encode(req.getRemoteAddr(), charset));

        final URLConnection connection = new URL(reCaptchaURL + "?" + reCaptchaQuery).openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        String response = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
            @Override
            public InputStream getInput() throws IOException {
                return connection.getInputStream();
            }
        }, Charsets.UTF_8));

        try {
            JSONObject JSONResponse = new JSONObject(response);
            if (!JSONResponse.getBoolean("success")) {
                resp.sendRedirect("/contactUs?captchaError=1");
                return;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            resp.sendRedirect("/contactUs?captchaError=1");
            return;
        }
    }

    feedback.setProperty("name", name);
    feedback.setProperty("school", school);
    feedback.setProperty("email", email);
    feedback.setProperty("comment", new Text(comment));
    feedback.setProperty("resolved", false);

    Transaction txn = datastore.beginTransaction();
    try {
        datastore.put(feedback);
        txn.commit();

        Session session = Session.getDefaultInstance(new Properties(), null);
        String appEngineEmail = (String) contestInfo.getProperty("account");

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(appEngineEmail, "Tournament Website Admin"));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress((String) contestInfo.getProperty("email"), "Contest Administrator"));
            msg.setSubject("Question about tournament from " + name);
            msg.setReplyTo(new InternetAddress[] { new InternetAddress(req.getParameter("email"), name),
                    new InternetAddress(appEngineEmail, "Tournament Website Admin") });

            VelocityEngine ve = new VelocityEngine();
            ve.init();

            VelocityContext context = new VelocityContext();
            context.put("name", name);
            context.put("email", email);
            context.put("school", school);
            context.put("message", comment);

            StringWriter sw = new StringWriter();
            Velocity.evaluate(context, sw, "questionEmail",
                    ((Text) contestInfo.getProperty("questionEmail")).getValue());
            msg.setContent(sw.toString(), "text/html");
            Transport.send(msg);
        } catch (MessagingException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            return;
        }

        resp.sendRedirect("/contactUs?updated=1");
        sess.invalidate();
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
    } finally {
        if (txn.isActive()) {
            txn.rollback();
        }
    }
}

From source file:au.aurin.org.controller.RestController.java

public Boolean sendEmail(final String randomUUIDString, final String password, final String email,
        final List<String> lstApps, final String fullName) throws IOException {
    final String clink = classmail.getUrl() + "authchangepassword/" + randomUUIDString;

    logger.info("Starting sending Email to:" + email);
    String msg = "";

    if (!fullName.equals("")) {
        msg = msg + "Dear " + fullName + "<br>";
    }/*from  w w  w .  j  a  v  a2s.  co  m*/
    Boolean lswWhatIf = false;
    if (lstApps != null) {
        //msg = msg + "You have been given access to the following applications: <br>";
        msg = msg + "<br>You have been given access to the following applications: <br>";
        for (final String st : lstApps) {
            if (st.toLowerCase().contains("whatif") || st.toLowerCase().contains("what if")) {

                lswWhatIf = true;
            }
            msg = "<br>" + msg + st + "<br>";
        }

    }

    msg = msg + "<br>Your current password is : " + password
            + " <br> To customise the password please change it using link below: <br> <a href='" + clink
            + "'> change password </a><br><br>After changing your password you can log in to the applications using your email and password. ";

    final String subject = "AURIN Workbench Access";

    final String from = classmail.getFrom();
    final String to = email;

    if (lswWhatIf == true) {
        msg = msg
                + "<br><br>If you require further support to establish a project within Online WhatIf please email your request to support@aurin.org.au";
        msg = msg + "<br>For other related requests please contact one of the members of the project team.";
        msg = msg + "<br><br>Kind Regards,";
        msg = msg + "<br>The Online WhatIf team<br>";
        msg = msg
                + "<br><strong>Prof Christopher Pettit</strong>&nbsp;&nbsp;&nbsp;&nbsp;Online WhatIf Project Director, City Futures (c.pettit@unsw.edu.au)";
        msg = msg
                + "<br><strong>Claudia Pelizaro</strong>&nbsp;&nbsp;&nbsp;&nbsp;Online WhatIf Project Manager, AURIN (claudia.pelizaro@unimelb.edu.au)";
        msg = msg
                + "<br><strong>Andrew Dingjan</strong>&nbsp;&nbsp;&nbsp;&nbsp;Director, AURIN (andrew.dingjan@unimelb.edu.au)";
        msg = msg
                + "<br><strong>Serryn Eagleson</strong>&nbsp;&nbsp;&nbsp;&nbsp;Manager Data and Business Analytics (serrynle@unimelb.edu.au)";

    } else {
        msg = msg + "<br><br>Kind Regards,";
        msg = msg + "<br>The AURIN Workbench team";
    }

    try {
        final Message message = new MimeMessage(getSession());

        message.addRecipient(RecipientType.TO, new InternetAddress(to));
        message.addFrom(new InternetAddress[] { new InternetAddress(from) });

        message.setSubject(subject);
        message.setContent(msg, "text/html");

        //////////////////////////////////
        final MimeMultipart multipart = new MimeMultipart("related");
        final BodyPart messageBodyPart = new MimeBodyPart();
        //final String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";

        msg = msg + "<br><br><img src=\"cid:AbcXyz123\" />";
        //msg = msg + "<img src=\"cid:image\">";
        messageBodyPart.setContent(msg, "text/html");
        // add it
        multipart.addBodyPart(messageBodyPart);

        /////// second part (the image)
        //      messageBodyPart = new MimeBodyPart();
        final URL peopleresource = getClass().getResource("/logo.jpg");
        logger.info(peopleresource.getPath());
        //            final DataSource fds = new FileDataSource(
        //                peopleresource.getPath());
        //
        //      messageBodyPart.setDataHandler(new DataHandler(fds));
        //      messageBodyPart.setHeader("Content-ID", "<image>");
        //      // add image to the multipart
        //      //multipart.addBodyPart(messageBodyPart);

        ///////////
        final MimeBodyPart imagePart = new MimeBodyPart();
        imagePart.attachFile(peopleresource.getPath());
        //      final String cid = "1";
        //      imagePart.setContentID("<" + cid + ">");
        imagePart.setHeader("Content-ID", "AbcXyz123");
        imagePart.setDisposition(MimeBodyPart.INLINE);
        multipart.addBodyPart(imagePart);

        // put everything together
        message.setContent(multipart);
        ////////////////////////////////

        Transport.send(message);
        logger.info("Email sent to:" + email);
    } catch (final Exception mex) {
        logger.info(mex.toString());
        return false;
    }

    return true;
}

From source file:org.apache.roller.weblogger.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type./*ww  w.j a  v  a 2  s . c  o m*/
 *
 * @param from e-mail address of sender
 * @param to e-mail address(es) of recipients
 * @param subject subject of e-mail
 * @param content the body of the e-mail
 * @param mimeType type of message, i.e. text/plain or text/html
 * @throws MessagingException the exception to indicate failure
 */
public static void sendMessage(String from, String[] to, String[] cc, String[] bcc, String subject,
        String content, String mimeType) throws MessagingException {

    MailProvider mailProvider = WebloggerStartup.getMailProvider();
    if (mailProvider == null) {
        return;
    }

    Session session = mailProvider.getSession();
    Message message = new MimeMessage(session);

    // n.b. any default from address is expected to be determined by caller.
    if (!StringUtils.isEmpty(from)) {
        InternetAddress sentFrom = new InternetAddress(from);
        message.setFrom(sentFrom);
        if (log.isDebugEnabled())
            log.debug("e-mail from: " + sentFrom);
    }

    if (to != null) {
        InternetAddress[] sendTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
            if (log.isDebugEnabled())
                log.debug("sending e-mail to: " + to[i]);
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    }

    if (cc != null) {
        InternetAddress[] copyTo = new InternetAddress[cc.length];

        for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]);
            if (log.isDebugEnabled())
                log.debug("copying e-mail to: " + cc[i]);
        }
        message.setRecipients(Message.RecipientType.CC, copyTo);
    }

    if (bcc != null) {
        InternetAddress[] copyTo = new InternetAddress[bcc.length];

        for (int i = 0; i < bcc.length; i++) {
            copyTo[i] = new InternetAddress(bcc[i]);
            if (log.isDebugEnabled())
                log.debug("blind copying e-mail to: " + bcc[i]);
        }
        message.setRecipients(Message.RecipientType.BCC, copyTo);
    }
    message.setSubject((subject == null) ? "(no subject)" : subject);
    message.setContent(content, mimeType);
    message.setSentDate(new java.util.Date());

    // First collect all the addresses together.
    Address[] remainingAddresses = message.getAllRecipients();
    int nAddresses = remainingAddresses.length;
    boolean bFailedToSome = false;

    SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

    Transport transport = mailProvider.getTransport();

    // Try to send while there remain some potentially good addresses
    try {
        do {
            // Avoid a loop if we are stuck
            nAddresses = remainingAddresses.length;

            try {
                // Send to the list of remaining addresses, ignoring the addresses attached to the message
                transport.sendMessage(message, remainingAddresses);
            } catch (SendFailedException ex) {
                bFailedToSome = true;
                sendex.setNextException(ex);

                // Extract the remaining potentially good addresses
                remainingAddresses = ex.getValidUnsentAddresses();
            }
        } while (remainingAddresses != null && remainingAddresses.length > 0
                && remainingAddresses.length != nAddresses);

    } finally {
        transport.close();
    }

    if (bFailedToSome)
        throw sendex;
}

From source file:com.funambol.email.items.manager.PopEntityManager.java

/**
 * This method creates an email with only header to save in
 * the local DB.//from   ww w  . j av  a2s.  c om
 *
 * @param session Mail Server session
 * @param msg complete message
 * @return msgForDB Message with only header
 * @throws EntityException
 */
private Message createMessageForDB(Message msg, String from, String firstname, String lastname)
        throws EntityException {

    Message msgForDB = null;

    try {

        // save old Message-ID
        String mid = Utility.getHeaderMessageID(msg);

        msgForDB = new MimeMessage(this.pmsw.getSession());

        // header
        MessageCreator.setNewHeaderSent(msgForDB, msg, from, firstname, lastname);

        // default empty content
        msgForDB.setContent(Def.CONTENT_BODY, Def.CONTENT_CONTENTTYPE);

        msgForDB.saveChanges();

        // the save message command change the message-ID
        msgForDB.setHeader(Def.HEADER_MESSAGE_ID, mid);

    } catch (MessagingException me) {
        throw new EntityException(me);
    }

    return msgForDB;

}

From source file:org.apache.nifi.processors.standard.PutEmail.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;/*from   w w  w.j  a  va2 s. com*/
    }

    final Properties properties = this.getMailPropertiesFromFlowFile(context, flowFile);

    final Session mailSession = this.createMailSession(properties);

    final Message message = new MimeMessage(mailSession);
    final ComponentLog logger = getLogger();

    try {
        message.addFrom(toInetAddresses(context, flowFile, FROM));
        message.setRecipients(RecipientType.TO, toInetAddresses(context, flowFile, TO));
        message.setRecipients(RecipientType.CC, toInetAddresses(context, flowFile, CC));
        message.setRecipients(RecipientType.BCC, toInetAddresses(context, flowFile, BCC));

        message.setHeader("X-Mailer",
                context.getProperty(HEADER_XMAILER).evaluateAttributeExpressions(flowFile).getValue());
        message.setSubject(context.getProperty(SUBJECT).evaluateAttributeExpressions(flowFile).getValue());
        String messageText = context.getProperty(MESSAGE).evaluateAttributeExpressions(flowFile).getValue();

        if (context.getProperty(INCLUDE_ALL_ATTRIBUTES).asBoolean()) {
            messageText = formatAttributes(flowFile, messageText);
        }

        String contentType = context.getProperty(CONTENT_TYPE).evaluateAttributeExpressions(flowFile)
                .getValue();
        message.setContent(messageText, contentType);
        message.setSentDate(new Date());

        if (context.getProperty(ATTACH_FILE).asBoolean()) {
            final MimeBodyPart mimeText = new PreencodedMimeBodyPart("base64");
            mimeText.setDataHandler(new DataHandler(new ByteArrayDataSource(
                    Base64.encodeBase64(messageText.getBytes("UTF-8")), contentType + "; charset=\"utf-8\"")));
            final MimeBodyPart mimeFile = new MimeBodyPart();
            session.read(flowFile, new InputStreamCallback() {
                @Override
                public void process(final InputStream stream) throws IOException {
                    try {
                        mimeFile.setDataHandler(
                                new DataHandler(new ByteArrayDataSource(stream, "application/octet-stream")));
                    } catch (final Exception e) {
                        throw new IOException(e);
                    }
                }
            });

            mimeFile.setFileName(flowFile.getAttribute(CoreAttributes.FILENAME.key()));
            MimeMultipart multipart = new MimeMultipart();
            multipart.addBodyPart(mimeText);
            multipart.addBodyPart(mimeFile);
            message.setContent(multipart);
        }

        send(message);

        session.getProvenanceReporter().send(flowFile, "mailto:" + message.getAllRecipients()[0].toString());
        session.transfer(flowFile, REL_SUCCESS);
        logger.info("Sent email as a result of receiving {}", new Object[] { flowFile });
    } catch (final ProcessException | MessagingException | IOException e) {
        context.yield();
        logger.error("Failed to send email for {}: {}; routing to failure",
                new Object[] { flowFile, e.getMessage() }, e);
        session.transfer(flowFile, REL_FAILURE);
    }
}

From source file:contestWebsite.Registration.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity contestInfo = Retrieve.contestInfo();

    Map<String, String[]> params = new HashMap<String, String[]>(req.getParameterMap());
    for (Entry<String, String[]> param : params.entrySet()) {
        if (!"studentData".equals(param.getKey())) {
            params.put(param.getKey(), new String[] { escapeHtml4(param.getValue()[0]) });
        }//from   ww  w .j  av  a 2  s. c  o m
    }

    String registrationType = params.get("registrationType")[0];
    String account = "no";
    if (params.containsKey("account")) {
        account = "yes";
    }
    String email = params.containsKey("email") && params.get("email")[0].length() > 0
            ? params.get("email")[0].toLowerCase().trim()
            : null;
    String schoolLevel = params.get("schoolLevel")[0];
    String schoolName = params.get("schoolName")[0].trim();
    String name = params.get("name")[0].trim();
    String classification = params.containsKey("classification") ? params.get("classification")[0] : "";
    String studentData = req.getParameter("studentData");
    String password = null;
    String confPassword = null;

    UserCookie userCookie = UserCookie.getCookie(req);
    boolean loggedIn = userCookie != null && userCookie.authenticate();
    if ((!loggedIn || !userCookie.isAdmin()) && email == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "E-Mail Address parameter ('email') must be specified");
        return;
    }

    HttpSession sess = req.getSession(true);
    sess.setAttribute("registrationType", registrationType);
    sess.setAttribute("account", account);
    sess.setAttribute("account", account);
    sess.setAttribute("name", name);
    sess.setAttribute("classification", classification);
    sess.setAttribute("schoolName", schoolName);
    sess.setAttribute("schoolLevel", schoolLevel);
    sess.setAttribute("email", email);
    sess.setAttribute("studentData", studentData);

    boolean reCaptchaResponse = false;
    if (!(Boolean) sess.getAttribute("nocaptcha")) {
        URL reCaptchaURL = new URL("https://www.google.com/recaptcha/api/siteverify");
        String charset = java.nio.charset.StandardCharsets.UTF_8.name();
        String reCaptchaQuery = String.format("secret=%s&response=%s&remoteip=%s",
                URLEncoder.encode((String) contestInfo.getProperty("privateKey"), charset),
                URLEncoder.encode(req.getParameter("g-recaptcha-response"), charset),
                URLEncoder.encode(req.getRemoteAddr(), charset));

        final URLConnection connection = new URL(reCaptchaURL + "?" + reCaptchaQuery).openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        String response = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
            @Override
            public InputStream getInput() throws IOException {
                return connection.getInputStream();
            }
        }, Charsets.UTF_8));

        try {
            JSONObject JSONResponse = new JSONObject(response);
            reCaptchaResponse = JSONResponse.getBoolean("success");
        } catch (JSONException e) {
            e.printStackTrace();
            resp.sendRedirect("/contactUs?captchaError=1");
            return;
        }
    }

    if (!(Boolean) sess.getAttribute("nocaptcha") && !reCaptchaResponse) {
        resp.sendRedirect("/registration?captchaError=1");
    } else {
        if (account.equals("yes")) {
            password = params.get("password")[0];
            confPassword = params.get("confPassword")[0];
        }

        Query query = new Query("registration")
                .setFilter(new FilterPredicate("email", FilterOperator.EQUAL, email)).setKeysOnly();
        List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1));

        if (users.size() != 0 && email != null || account.equals("yes") && !confPassword.equals(password)) {
            if (users.size() != 0) {
                resp.sendRedirect("/registration?userError=1");
            } else if (!params.get("confPassword")[0].equals(params.get("password")[0])) {
                resp.sendRedirect("/registration?passwordError=1");
            } else {
                resp.sendRedirect("/registration?updated=1");
            }
        } else {
            Entity registration = new Entity("registration");
            registration.setProperty("registrationType", registrationType);
            registration.setProperty("account", account);
            registration.setProperty("schoolName", schoolName);
            registration.setProperty("schoolLevel", schoolLevel);
            registration.setProperty("name", name);
            registration.setProperty("classification", classification);
            registration.setProperty("studentData", new Text(studentData));
            registration.setProperty("email", email);
            registration.setProperty("paid", "");
            registration.setProperty("timestamp", new Date());

            JSONArray regData = null;
            try {
                regData = new JSONArray(studentData);
            } catch (JSONException e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                return;
            }

            long price = (Long) contestInfo.getProperty("price");
            int cost = (int) (0 * price);

            for (int i = 0; i < regData.length(); i++) {
                try {
                    JSONObject studentRegData = regData.getJSONObject(i);
                    for (Subject subject : Subject.values()) {
                        cost += price * (studentRegData.getBoolean(subject.toString()) ? 1 : 0);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                    return;
                }
            }

            registration.setProperty("cost", cost);

            Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true));
            try {
                datastore.put(registration);

                if (account.equals("yes") && password != null && password.length() > 0 && email != null) {
                    Entity user = new Entity("user");
                    String hash = Password.getSaltedHash(password);
                    user.setProperty("name", name);
                    user.setProperty("school", schoolName);
                    user.setProperty("schoolLevel", schoolLevel);
                    user.setProperty("user-id", email);
                    user.setProperty("salt", hash.split("\\$")[0]);
                    user.setProperty("hash", hash.split("\\$")[1]);
                    datastore.put(user);
                }

                txn.commit();

                sess.setAttribute("props", registration.getProperties());

                if (email != null) {
                    Session session = Session.getDefaultInstance(new Properties(), null);
                    String appEngineEmail = (String) contestInfo.getProperty("account");

                    String url = req.getRequestURL().toString();
                    url = url.substring(0, url.indexOf("/", 7));

                    try {
                        Message msg = new MimeMessage(session);
                        msg.setFrom(new InternetAddress(appEngineEmail, "Tournament Website Admin"));
                        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, name));
                        msg.setSubject("Thank you for your registration!");

                        VelocityEngine ve = new VelocityEngine();
                        ve.init();

                        VelocityContext context = new VelocityContext();
                        context.put("name", name);
                        context.put("url", url);
                        context.put("cost", cost);
                        context.put("title", contestInfo.getProperty("title"));
                        context.put("account", account.equals("yes"));

                        StringWriter sw = new StringWriter();
                        Velocity.evaluate(context, sw, "registrationEmail",
                                ((Text) contestInfo.getProperty("registrationEmail")).getValue());
                        msg.setContent(sw.toString(), "text/html");
                        Transport.send(msg);
                    } catch (MessagingException e) {
                        e.printStackTrace();
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                        return;
                    }
                }

                resp.sendRedirect("/registration?updated=1");
            } catch (Exception e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            } finally {
                if (txn.isActive()) {
                    txn.rollback();
                }
            }
        }
    }
}