Example usage for javax.mail Message addFrom

List of usage examples for javax.mail Message addFrom

Introduction

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

Prototype

public abstract void addFrom(Address[] addresses) throws MessagingException;

Source Link

Document

Add these addresses to the existing "From" attribute

Usage

From source file:com.nridge.core.app.mail.MailManager.java

/**
 * If the property "delivery_enabled" is <i>true</i>, then this method
 * will generate an email message that includes subject, message and
 * attachments to the recipient list.  You can use the convenience
 * methods <i>lookupFromAddress()</i>, <i>createRecipientList()</i>
 * and <i>createAttachmentList()</i> for parameter building assistance.
 *
 * @param aFromAddress Source email address.
 * @param aRecipientList List of recipient email addresses.
 * @param aSubject Subject of the email message.
 * @param aMessage Messsage./*from www .j  a  v a  2  s  .co m*/
 * @param anAttachmentFiles List of file attachments or <i>null</i> for none.
 *
 * @see <a href="https://www.tutorialspoint.com/javamail_api/javamail_api_send_email_with_attachment.htm">JavaMail API Attachments</a>
 * @see <a href="https://stackoverflow.com/questions/6756162/how-do-i-send-mail-with-both-plain-text-as-well-as-html-text-so-that-each-mail-r">JavaMail API MIME Types</a>
 *
 * @throws IOException I/O related error condition.
 * @throws NSException Missing configuration properties.
 * @throws MessagingException Message subsystem error condition.
 */
public void sendMessage(String aFromAddress, ArrayList<String> aRecipientList, String aSubject, String aMessage,
        ArrayList<String> anAttachmentFiles)

        throws IOException, NSException, MessagingException {
    InternetAddress internetAddressFrom, internetAddressTo;
    Logger appLogger = mAppMgr.getLogger(this, "sendMessage");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (isCfgStringTrue("delivery_enabled")) {
        if ((StringUtils.isNotEmpty(aFromAddress)) && (aRecipientList.size() > 0)
                && (StringUtils.isNotEmpty(aSubject)) && (StringUtils.isNotEmpty(aMessage))) {
            initialize();

            Message mimeMessage = new MimeMessage(mMailSession);
            internetAddressFrom = new InternetAddress(aFromAddress);
            mimeMessage.addFrom(new InternetAddress[] { internetAddressFrom });
            for (String mailAddressTo : aRecipientList) {
                internetAddressTo = new InternetAddress(mailAddressTo);
                mimeMessage.addRecipient(MimeMessage.RecipientType.TO, internetAddressTo);
            }
            mimeMessage.setSubject(aSubject);

            // The following logic create a multi-part message and adds the attachment to it.

            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(aMessage);
            //                messageBodyPart.setContent(aMessage, "text/html");
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            if ((anAttachmentFiles != null) && (anAttachmentFiles.size() > 0)) {
                for (String pathFileName : anAttachmentFiles) {
                    File attachmentFile = new File(pathFileName);
                    if (attachmentFile.exists()) {
                        messageBodyPart = new MimeBodyPart();
                        DataSource fileDataSource = new FileDataSource(pathFileName);
                        messageBodyPart.setDataHandler(new DataHandler(fileDataSource));
                        messageBodyPart.setFileName(attachmentFile.getName());
                        multipart.addBodyPart(messageBodyPart);
                    }
                }
                appLogger.debug(String.format("Mail Message (%s): %s - with attachments", aSubject, aMessage));
            } else
                appLogger.debug(String.format("Mail Message (%s): %s", aSubject, aMessage));

            mimeMessage.setContent(multipart);
            Transport.send(mimeMessage);
        } else
            throw new NSException("Valid from, recipient, subject and message are required parameters.");
    } else
        appLogger.warn("Email delivery is not enabled - no message will be sent.");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

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>";
    }//w ww  .jav  a2  s.c o  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:com.nridge.core.app.mail.MailManager.java

/**
 * If the property "delivery_enabled" is <i>true</i>, then this
 * method will deliver the subject and message via an email
 * transport (e.g. SMTP)./*w  ww .  ja  va 2  s  .c o m*/
 *
 * @param aSubject Message subject.
 * @param aMessage Message content.
 *
 * @throws IOException I/O related error condition.
 * @throws NSException Missing configuration properties.
 * @throws MessagingException Message subsystem error condition.
 */
public void sendMessage(String aSubject, String aMessage) throws IOException, NSException, MessagingException {
    InternetAddress internetAddressFrom, internetAddressTo;
    Logger appLogger = mAppMgr.getLogger(this, "sendMessage");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (isCfgStringTrue("delivery_enabled")) {
        if ((StringUtils.isNotEmpty(aSubject)) && (StringUtils.isNotEmpty(aMessage))) {
            initialize();

            String propertyName = "address_to";
            Message mimeMessage = new MimeMessage(mMailSession);
            if (mAppMgr.isPropertyMultiValue(getCfgString(propertyName))) {
                String[] addressToArray = mAppMgr.getStringArray(getCfgString(propertyName));
                for (String mailAddressTo : addressToArray) {
                    internetAddressTo = new InternetAddress(mailAddressTo);
                    mimeMessage.addRecipient(MimeMessage.RecipientType.TO, internetAddressTo);
                }
            } else {
                String mailAddressTo = getCfgString(propertyName);
                if (StringUtils.isEmpty(mailAddressTo)) {
                    String msgStr = String.format("Mail Manager property '%s' is undefined.",
                            mCfgPropertyPrefix + "." + propertyName);
                    appLogger.error(msgStr);
                    throw new NSException(msgStr);
                }
                internetAddressTo = new InternetAddress(mailAddressTo);
                mimeMessage.addRecipient(MimeMessage.RecipientType.TO, internetAddressTo);
            }
            propertyName = "address_from";
            String mailAddressFrom = getCfgString(propertyName);
            if (StringUtils.isEmpty(mailAddressFrom)) {
                String msgStr = String.format("Mail Manager property '%s' is undefined.",
                        mCfgPropertyPrefix + "." + propertyName);
                appLogger.error(msgStr);
                throw new NSException(msgStr);
            }
            internetAddressFrom = new InternetAddress(mailAddressFrom);
            mimeMessage.addFrom(new InternetAddress[] { internetAddressFrom });
            mimeMessage.setSubject(aSubject);
            mimeMessage.setContent(aMessage, "text/plain");

            appLogger.debug(String.format("Mail Message (%s): %s", aSubject, aMessage));

            Transport.send(mimeMessage);
        } else
            throw new NSException("Subject and message are required parameters.");
    } else
        appLogger.warn("Email delivery is not enabled - no message will be sent.");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:de.innovationgate.wgpublisher.WGACore.java

public void send(WGAMailNotification notification) {
    WGAMailConfiguration config = getMailConfig();

    if (config != null && config.isEnableAdminNotifications()) {
        try {//from   ww w. j  av  a2s  . c  om
            Message msg = new MimeMessage(config.createMailSession());

            // set recipient and from address
            String toAddress = config.getToAddress();
            if (toAddress == null) {
                getLog().error(
                        "Unable to send wga admin notification because no recipient address is configured");
                return;
            }

            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
            InternetAddress[] fromAddr = new InternetAddress[1];
            fromAddr[0] = new InternetAddress(config.getFromAddress());
            msg.addFrom(fromAddr);

            msg.setSentDate(new Date());

            InetAddress localMachine = InetAddress.getLocalHost();
            String hostname = localMachine.getHostName();
            String serverName = getWgaConfiguration().getServerName();
            if (serverName == null) {
                serverName = hostname;
            }

            msg.setSubject(notification.getSubject());

            msg.setHeader(WGAMailNotification.HEADERFIELD_TYPE, notification.getType());

            MimeMultipart content = new MimeMultipart();
            MimeBodyPart body = new MimeBodyPart();

            StringBuffer strBody = new StringBuffer();
            strBody.append("<html><head></head><body style=\"color:#808080\">");
            strBody.append(notification.getMessage());
            String rootURL = getWgaConfiguration().getRootURL();
            if (rootURL != null) {
                //strBody.append("<br><br>");
                strBody.append("<p><a href=\"" + rootURL + "/plugin-admin\">" + WGABrand.getName()
                        + " admin client ...</a></p>");
            }
            // append footer
            strBody.append("<br><br><b>System information:</b><br><br>");
            strBody.append("<b>Server:</b> " + serverName + " / " + WGACore.getReleaseString() + "<br>");
            strBody.append("<b>Host:</b> " + hostname + "<br>");
            strBody.append("<b>Operation System:</b> " + System.getProperty("os.name") + " Version "
                    + System.getProperty("os.version") + " (" + System.getProperty("os.arch") + ")<br>");
            strBody.append("<b>Java virtual machine:</b> " + System.getProperty("java.vm.name") + " Version "
                    + System.getProperty("java.vm.version") + " (" + System.getProperty("java.vm.vendor")
                    + ")");

            strBody.append("</body></html>");
            body.setText(strBody.toString());
            body.setHeader("MIME-Version", "1.0");
            body.setHeader("Content-Type", "text/html");

            content.addBodyPart(body);
            AppLog appLog = WGA.get(this).service(AppLog.class);

            if (notification.isAttachLogfile()) {
                MimeBodyPart attachmentBody = new MimeBodyPart();

                StringWriter applog = new StringWriter();
                int applogSize = appLog.getLinesCount();
                int offset = applogSize - notification.getLogfileLines();
                if (offset < 0) {
                    offset = 1;
                }
                appLog.writePage(offset, notification.getLogfileLines(), applog, LogLevel.LEVEL_INFO, false);

                attachmentBody.setDataHandler(new DataHandler(applog.toString(), "text/plain"));
                attachmentBody.setFileName("wga.log");
                content.addBodyPart(attachmentBody);
            }
            msg.setContent(content);

            // Send mail
            Thread mailThread = new Thread(new AsyncMailSender(msg), "WGAMailSender");
            mailThread.start();
        } catch (Exception e) {
            getLog().error("Unable to send wga admin notification.", e);
        }
    }
}

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   ww  w. j av  a 2s .  co m
    }

    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:org.jahia.services.workflow.jbpm.custom.email.JBPMMailProducer.java

/**
 * Fills the <code>from</code> attribute of the given email. The sender addresses are an
 * optional element in the mail template. If absent, each mail server supplies the current
 * user's email address./*from  ww w  .  j av  a  2 s  .co  m*/
 *
 * @see {@link InternetAddress#getLocalAddress(Session)}
 */
protected void fillFrom(MailTemplate template, Message email, WorkItem workItem, JCRSessionWrapper session)
        throws Exception {
    AddressTemplate fromTemplate = template.getFrom();
    // "from" attribute is optional
    if (fromTemplate == null)
        return;

    // resolve and parse addresses
    String addresses = fromTemplate.getAddresses();
    if (addresses != null) {
        addresses = evaluateExpression(workItem, addresses, session);
        // non-strict parsing applies to a list of mail addresses entered by a human
        email.addFrom(InternetAddress.parse(addresses, false));
    }

    // resolve and tokenize users
    String userList = fromTemplate.getUsers();
    if (userList != null) {
        String[] userIds = tokenizeActors(userList, workItem, session);
        List<User> users = new ArrayList<User>();
        for (String userId : userIds) {
            users.add(taskIdentityService.getUserById(userId));
        }
        email.addFrom(getAddresses(users));
    }

    // resolve and tokenize groups
    String groupList = fromTemplate.getGroups();
    if (groupList != null) {
        for (String groupId : tokenizeActors(groupList, workItem, session)) {
            org.kie.api.task.model.Group group = taskIdentityService.getGroupById(groupId);
            email.addFrom(getAddresses(group));
        }
    }
}

From source file:org.jahia.services.workflow.jbpm.JBPMMailProducer.java

/**
   * Fills the <code>from</code> attribute of the given email. The sender addresses are an
   * optional element in the mail template. If absent, each mail server supplies the current
   * user's email address.//from  w ww . ja v a2  s  .  c  om
   *
   * @see {@link InternetAddress#getLocalAddress(Session)}
 */
protected void fillFrom(Message email, Execution execution, JCRSessionWrapper session)
        throws MessagingException {
    try {
        AddressTemplate fromTemplate = getTemplate().getFrom();
        // "from" attribute is optional
        if (fromTemplate == null)
            return;

        // resolve and parse addresses
        String addresses = fromTemplate.getAddresses();
        if (addresses != null) {
            addresses = evaluateExpression(execution, addresses, session);
            // non-strict parsing applies to a list of mail addresses entered by a human
            email.addFrom(InternetAddress.parse(addresses, false));
        }

        EnvironmentImpl environment = EnvironmentImpl.getCurrent();
        IdentitySession identitySession = environment.get(IdentitySession.class);
        AddressResolver addressResolver = environment.get(AddressResolver.class);

        // resolve and tokenize users
        String userList = fromTemplate.getUsers();
        if (userList != null) {
            String[] userIds = tokenizeActors(userList, execution, session);
            List<User> users = identitySession.findUsersById(userIds);
            email.addFrom(resolveAddresses(users, addressResolver));
        }

        // resolve and tokenize groups
        String groupList = fromTemplate.getGroups();
        if (groupList != null) {
            for (String groupId : tokenizeActors(groupList, execution, session)) {
                Group group = identitySession.findGroupById(groupId);
                email.addFrom(addressResolver.resolveAddresses(group));
            }
        }
    } catch (ScriptException e) {
        logger.error(e.getMessage(), e);
    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:org.nuxeo.labs.operations.notification.AdvancedSendEmail.java

protected void addFromEmails(Message msg) throws ClientException, MessagingException {
    for (String email : getEmails(from, "FROM")) {
        msg.addFrom(email);
    }// www .  j a  v a  2  s  .  c o m
}

From source file:org.orbeon.oxf.processor.EmailProcessor.java

public void start(PipelineContext pipelineContext) {
    try {//  www  . j  a  va  2  s . co  m
        final Document dataDocument = readInputAsDOM4J(pipelineContext, INPUT_DATA);
        final Element messageElement = dataDocument.getRootElement();

        // Get system id (will likely be null if document is generated dynamically)
        final LocationData locationData = (LocationData) messageElement.getData();
        final String dataInputSystemId = locationData.getSystemID();

        // Set SMTP host
        final Properties properties = new Properties();
        final String testSmtpHostProperty = getPropertySet().getString(EMAIL_TEST_SMTP_HOST);

        if (testSmtpHostProperty != null) {
            // Test SMTP Host from properties overrides the local configuration
            properties.setProperty("mail.smtp.host", testSmtpHostProperty);
        } else {
            // Try regular config parameter and property
            String host = messageElement.element("smtp-host").getTextTrim();
            if (host != null && !host.equals("")) {
                // Precedence goes to the local config parameter
                properties.setProperty("mail.smtp.host", host);
            } else {
                // Otherwise try to use a property
                host = getPropertySet().getString(EMAIL_SMTP_HOST);
                if (host == null)
                    host = getPropertySet().getString(EMAIL_HOST_DEPRECATED);
                if (host == null)
                    throw new OXFException("Could not find SMTP host in configuration or in properties");
                properties.setProperty("mail.smtp.host", host);

            }
        }

        // Create session
        final Session session;
        {
            // Get credentials
            final String usernameTrimmed;
            final String passwordTrimmed;
            {
                final Element credentials = messageElement.element("credentials");
                if (credentials != null) {
                    final Element usernameElement = credentials.element("username");
                    final Element passwordElement = credentials.element("password");
                    usernameTrimmed = (usernameElement != null) ? usernameElement.getStringValue().trim()
                            : null;
                    passwordTrimmed = (passwordElement != null) ? passwordElement.getStringValue().trim() : "";
                } else {
                    usernameTrimmed = null;
                    passwordTrimmed = null;
                }
            }

            // Check if credentials are supplied
            if (StringUtils.isNotEmpty(usernameTrimmed)) {
                // NOTE: A blank username doesn't trigger authentication

                if (logger.isInfoEnabled())
                    logger.info("Authentication");
                // Set the auth property to true
                properties.setProperty("mail.smtp.auth", "true");

                if (logger.isInfoEnabled())
                    logger.info("Username: " + usernameTrimmed);

                // Create an authenticator
                final Authenticator authenticator = new SMTPAuthenticator(usernameTrimmed, passwordTrimmed);

                // Create session with authenticator
                session = Session.getInstance(properties, authenticator);
            } else {
                if (logger.isInfoEnabled())
                    logger.info("No Authentication");
                session = Session.getInstance(properties);
            }
        }

        // Create message
        final Message message = new MimeMessage(session);

        // Set From
        message.addFrom(createAddresses(messageElement.element("from")));

        // Set To
        String testToProperty = getPropertySet().getString(EMAIL_TEST_TO);
        if (testToProperty == null)
            testToProperty = getPropertySet().getString(EMAIL_FORCE_TO_DEPRECATED);

        if (testToProperty != null) {
            // Test To from properties overrides local configuration
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(testToProperty));
        } else {
            // Regular list of To elements
            for (final Element toElement : Dom4jUtils.elements(messageElement, "to")) {
                final InternetAddress[] addresses = createAddresses(toElement);
                message.addRecipients(Message.RecipientType.TO, addresses);
            }
        }

        // Set Cc
        for (final Element ccElement : Dom4jUtils.elements(messageElement, "cc")) {
            final InternetAddress[] addresses = createAddresses(ccElement);
            message.addRecipients(Message.RecipientType.CC, addresses);
        }

        // Set Bcc
        for (final Element bccElement : Dom4jUtils.elements(messageElement, "bcc")) {
            final InternetAddress[] addresses = createAddresses(bccElement);
            message.addRecipients(Message.RecipientType.BCC, addresses);
        }

        // Set headers if any
        for (final Element headerElement : Dom4jUtils.elements(messageElement, "header")) {
            final String headerName = headerElement.element("name").getTextTrim();
            final String headerValue = headerElement.element("value").getTextTrim();

            // NOTE: Use encodeText() in case there are non-ASCII characters
            message.addHeader(headerName,
                    MimeUtility.encodeText(headerValue, DEFAULT_CHARACTER_ENCODING, null));
        }

        // Set the email subject
        // The JavaMail spec is badly written and is not clear about whether this needs to be done here. But it
        // seems to use the platform's default charset, which we don't want to deal with. So we preemptively encode.
        // The result is pure ASCII so that setSubject() will not attempt to re-encode it.
        message.setSubject(MimeUtility.encodeText(messageElement.element("subject").getStringValue(),
                DEFAULT_CHARACTER_ENCODING, null));

        // Handle body
        final Element textElement = messageElement.element("text");
        final Element bodyElement = messageElement.element("body");

        if (textElement != null) {
            // Old deprecated mechanism (simple text body)
            message.setText(textElement.getStringValue());
        } else if (bodyElement != null) {
            // New mechanism with body and parts
            handleBody(pipelineContext, dataInputSystemId, message, bodyElement);
        } else {
            throw new OXFException("Main text or body element not found");// TODO: location info
        }

        // Send message
        final Transport transport = session.getTransport("smtp");
        Transport.send(message);
        transport.close();
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:org.webguitoolkit.messagebox.mail.MailChannel.java

@Override
public void send(IMessage message) {
    try {//w w  w .j  a v  a 2  s.  co m
        Message mail = new MimeMessage(getSession());

        mail.addFrom(new InternetAddress[] { new InternetAddress(message.getSender()) });
        Set<String> recipients = message.getRecipients();
        if (recipients.isEmpty())
            return;
        for (String recipient : recipients) {
            mail.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }

        mail.setSubject(message.getSubject());
        mail.setContent(message.getBody(), message.getContentType());

        Transport.send(mail);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}