Example usage for javax.mail.internet MimeMessage setContent

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

Introduction

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

Prototype

@Override
public void setContent(Object o, String type) throws MessagingException 

Source Link

Document

A convenience method for setting this Message's content.

Usage

From source file:nl.nn.adapterframework.senders.MailSenderOld.java

protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType,
        String messageBase64, String charset, Collection<Recipient> recipients,
        Collection<Attachment> attachments) throws SenderException {

    StringBuffer sb = new StringBuffer();

    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }//from   ww w.j  av  a2 s . com
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject
            + "] to #recipients [" + recipients.size() + "]");

    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }

    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }

    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }

        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }

        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Recipient recipient = (Recipient) iter.next();
            String value = recipient.value;
            String type = recipient.type;
            Message.RecipientType recipientType;
            if ("cc".equalsIgnoreCase(type)) {
                recipientType = Message.RecipientType.CC;
            } else if ("bcc".equalsIgnoreCase(type)) {
                recipientType = Message.RecipientType.BCC;
            } else {
                recipientType = Message.RecipientType.TO;
            }
            msg.addRecipient(recipientType, new InternetAddress(value));
            recipientsFound = true;
            if (log.isDebugEnabled()) {
                sb.append("[recipient [" + recipient + "]]");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }

        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");

        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);

            int counter = 0;
            iter = attachments.iterator();
            while (iter.hasNext()) {
                counter++;
                Attachment attachment = (Attachment) iter.next();
                Object value = attachment.getValue();
                String name = attachment.getName();
                if (StringUtils.isEmpty(name)) {
                    name = getDefaultAttachmentName() + counter;
                }
                log.debug("found attachment [" + attachment + "]");

                messageBodyPart = new MimeBodyPart();
                messageBodyPart.setFileName(name);

                if (value instanceof DataHandler) {
                    messageBodyPart.setDataHandler((DataHandler) value);
                } else {
                    messageBodyPart.setText((String) value);
                }

                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        }

        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}

From source file:nl.nn.adapterframework.senders.MailSender.java

protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType,
        String messageBase64, String charset, Collection recipients, Collection attachments)
        throws SenderException {

    StringBuffer sb = new StringBuffer();

    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }/*from w w  w . ja v a2 s. c o  m*/
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject
            + "] to #recipients [" + recipients.size() + "]");

    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }

    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }

    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }

        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }

        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Element recipientElement = (Element) iter.next();
            String recipient = XmlUtils.getStringValue(recipientElement);
            if (StringUtils.isNotEmpty(recipient)) {
                String typeAttr = recipientElement.getAttribute("type");
                Message.RecipientType recipientType = Message.RecipientType.TO;
                if ("cc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.CC;
                }
                if ("bcc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.BCC;
                }
                msg.addRecipient(recipientType, new InternetAddress(recipient));
                recipientsFound = true;
                if (log.isDebugEnabled()) {
                    sb.append("[recipient(" + typeAttr + ")=" + recipient + "]");
                }
            } else {
                log.debug("empty recipient found, ignoring");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }

        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");

        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);

            iter = attachments.iterator();
            while (iter.hasNext()) {
                Element attachmentElement = (Element) iter.next();
                String attachmentText = XmlUtils.getStringValue(attachmentElement);
                String attachmentName = attachmentElement.getAttribute("name");
                String attachmentUrl = attachmentElement.getAttribute("url");
                String attachmentType = attachmentElement.getAttribute("type");
                String attachmentBase64 = attachmentElement.getAttribute("base64");
                if (StringUtils.isEmpty(attachmentType)) {
                    attachmentType = getDefaultAttachmentType();
                }
                if (StringUtils.isEmpty(attachmentName)) {
                    attachmentName = getDefaultAttachmentName();
                }
                log.debug("found attachment [" + attachmentName + "] type [" + attachmentType + "] url ["
                        + attachmentUrl + "]contents [" + attachmentText + "]");

                messageBodyPart = new MimeBodyPart();

                DataSource attachmentDataSource;
                if (!StringUtils.isEmpty(attachmentUrl)) {
                    attachmentDataSource = new URLDataSource(new URL(attachmentUrl));
                    messageBodyPart.setDataHandler(new DataHandler(attachmentDataSource));
                }

                messageBodyPart.setFileName(attachmentName);

                if ("true".equalsIgnoreCase(attachmentBase64)) {
                    messageBodyPart.setDataHandler(decodeBase64(attachmentText));
                } else {
                    messageBodyPart.setText(attachmentText);
                }

                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        }

        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 * Creates the IMAP messages to be sent. Looks up access (email & pwd) from
 * LDAP, sets the values and returns the messages to be sent.
 * //from   ww  w.  j ava  2  s .c  om
 * @param session Mail session 
 * @param emailAddr From email address
 * @param request Request from PS
 * @return Array of messages
 * @throws Exception 
 */
private Message[] createMessage(Session session, String emailAddr, SetMessageRequestType request)
        throws Exception {

    /*
    //DBG ONLY - Check about CC entry.
    List<String> ctlist = request.getContactTo();
    if (!CommonUtil.listNullorEmpty(ctlist)) {
        System.out.println("===> createMessage: TO="+ ctlist.get(0));
    }
    ctlist = request.getContactCC();
    if (!CommonUtil.listNullorEmpty(ctlist)) {
        System.out.println("===> createMessage: CC="+ ctlist.get(0));
    }
    ctlist = request.getContactBCC();
    if (!CommonUtil.listNullorEmpty(ctlist)) {
        System.out.println("===> createMessage: BCC="+ ctlist.get(0));
    }
    */
    MimeMessage message = new MimeMessage(session);

    if (!CommonUtil.listNullorEmpty(request.getContactTo())) {
        message.setRecipients(Message.RecipientType.TO, getInetAddresses(request.getContactTo())); //getInetAddresses(request, "To"));
    }

    if (!CommonUtil.listNullorEmpty(request.getContactCC())) {
        message.setRecipients(Message.RecipientType.CC, getInetAddresses(request.getContactCC())); //getInetAddresses(request, "CC"));
    }

    if (!CommonUtil.listNullorEmpty(request.getContactBCC())) {
        message.setRecipients(Message.RecipientType.BCC, getInetAddresses(request.getContactBCC())); //getInetAddresses(request, "BCC"));
    }

    message.setSubject(request.getSubject());

    // Adding headers doesn't seem to be supported currently in zimbra. 
    // Adding patientId to body instead temporarily 
    // message.addHeader("X-PATIENTID", request.getPatientId());
    StringBuilder sb = new StringBuilder();

    // Only add in PATIENTID first line if there is a patientId in session.
    if (!CommonUtil.strNullorEmpty(request.getPatientId())) {
        sb.append("PATIENTID=").append(request.getPatientId()).append("\n");
    }

    if (CommonUtil.strNullorEmpty(request.getBody())) {
        sb.append("");
    } else {
        sb.append(request.getBody());
    }

    message.setContent(sb.toString(), "text/plain");
    message.setFrom(new InternetAddress(emailAddr));
    message.setSentDate(new Date());

    List<String> labelList = request.getLabels();
    if (labelList.size() > 0) {
        String label = labelList.get(0);
        if (label.equalsIgnoreCase("starred")) {
            message.setFlag(Flags.Flag.FLAGGED, true);
        }
    }
    Message[] msgArr = new Message[1];
    msgArr[0] = message;
    return msgArr;
}

From source file:com.flexoodb.common.FlexUtils.java

static public boolean sendMail(String host, int port, String from, String to, String subject, String msg)
        throws Exception {
    SMTPTransport transport = null;//w  w  w. j  a v a 2  s .c  o m
    boolean ok = false;
    try {
        InternetAddress[] rcptto = new InternetAddress[1];
        rcptto[0] = new InternetAddress(to);

        Properties props = System.getProperties();

        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port + "");

        javax.mail.Session session = javax.mail.Session.getDefaultInstance(props, null);

        transport = (SMTPTransport) session.getTransport("smtp");

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setContent(msg, "text/html");
        //Transport.send(message);

        transport.setLocalHost("REMOTE-CLIENT");
        transport.connect();
        transport.sendMessage(message, rcptto);

        ok = true;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            transport.close();
        } catch (Exception f) {
            f.printStackTrace();
        }
    }
    return ok;
}

From source file:com.flexoodb.common.FlexUtils.java

static public String sendMailShowResult(String host, int port, String from, String to, String subject,
        String msg) throws Exception {
    String response = "OK";

    SMTPTransport transport = null;/*from  w  w  w.j a  v  a  2  s. c om*/
    boolean ok = true;

    try {
        InternetAddress[] rcptto = new InternetAddress[1];
        rcptto[0] = new InternetAddress(to);

        Properties props = System.getProperties();

        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port + "");
        props.put("mail.smtp.connectiontimeout", "60000"); // 300000 original
        props.put("mail.smtp.timeout", "60000");
        props.put("mail.smtp.quitwait", "false");

        javax.mail.Session session = javax.mail.Session.getInstance(props);

        transport = (SMTPTransport) session.getTransport("smtp");

        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));

        message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setContent(msg, "text/html");
        //Transport.send(message);
        transport.setLocalHost("REMOTE-CLIENT");
        transport.connect();
        transport.sendMessage(message, rcptto);

    } catch (Exception e) {
        e.printStackTrace();
        ok = false;
    } finally {

        try {
            if (!ok) {
                response = "SENDING FAILED:" + transport.getLastServerResponse();
            } else {
                response = "SENDING SUCCESS:" + transport.getLastServerResponse();
            }

            transport.close();

        } catch (Exception f) {

        }

    }
    return response;
}

From source file:davmail.exchange.ews.EwsExchangeSession.java

/**
 * Get item content.//from w  w  w .j a  va2  s  . c om
 *
 * @param itemId EWS item id
 * @return item content as byte array
 * @throws IOException on error
 */
protected byte[] getContent(ItemId itemId) throws IOException {
    GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, true);
    byte[] mimeContent = null;
    try {
        executeMethod(getItemMethod);
        mimeContent = getItemMethod.getMimeContent();
    } catch (EWSException e) {
        LOGGER.warn("GetItem with MimeContent failed: " + e.getMessage());
    }
    if (getItemMethod.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
        throw new HttpNotFoundException("Item " + itemId + " not found");
    }
    if (mimeContent == null) {
        LOGGER.warn("MimeContent not available, trying to rebuild from properties");
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, false);
            getItemMethod.addAdditionalProperty(Field.get("contentclass"));
            getItemMethod.addAdditionalProperty(Field.get("message-id"));
            getItemMethod.addAdditionalProperty(Field.get("from"));
            getItemMethod.addAdditionalProperty(Field.get("to"));
            getItemMethod.addAdditionalProperty(Field.get("cc"));
            getItemMethod.addAdditionalProperty(Field.get("subject"));
            getItemMethod.addAdditionalProperty(Field.get("date"));
            getItemMethod.addAdditionalProperty(Field.get("body"));
            executeMethod(getItemMethod);
            EWSMethod.Item item = getItemMethod.getResponseItem();

            MimeMessage mimeMessage = new MimeMessage((Session) null);
            mimeMessage.addHeader("Content-class", item.get(Field.get("contentclass").getResponseName()));
            mimeMessage.setSentDate(parseDateFromExchange(item.get(Field.get("date").getResponseName())));
            mimeMessage.addHeader("From", item.get(Field.get("from").getResponseName()));
            mimeMessage.addHeader("To", item.get(Field.get("to").getResponseName()));
            mimeMessage.addHeader("Cc", item.get(Field.get("cc").getResponseName()));
            mimeMessage.setSubject(item.get(Field.get("subject").getResponseName()));
            String propertyValue = item.get(Field.get("body").getResponseName());
            if (propertyValue == null) {
                propertyValue = "";
            }
            mimeMessage.setContent(propertyValue, "text/html; charset=UTF-8");

            mimeMessage.writeTo(baos);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray()));
            }
            mimeContent = baos.toByteArray();

        } catch (IOException e2) {
            LOGGER.warn(e2);
        } catch (MessagingException e2) {
            LOGGER.warn(e2);
        }
        if (mimeContent == null) {
            throw new IOException("GetItem returned null MimeContent");
        }
    }
    return mimeContent;
}

From source file:com.flexoodb.common.FlexUtils.java

static public String sendMailShowResult(String host, int port, String fromname, String from, String to,
        String subject, String msg) throws Exception {
    String response = "OK";

    SMTPTransport transport = null;/*from  w  w  w .j a  v a 2s . c o  m*/
    boolean ok = true;

    try {
        InternetAddress[] rcptto = new InternetAddress[1];
        rcptto[0] = new InternetAddress(to);

        Properties props = System.getProperties();

        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port + "");
        props.put("mail.smtp.connectiontimeout", "60000"); // 300000 original
        props.put("mail.smtp.timeout", "60000");
        props.put("mail.smtp.quitwait", "false");

        javax.mail.Session session = javax.mail.Session.getInstance(props);

        transport = (SMTPTransport) session.getTransport("smtp");

        MimeMessage message = new MimeMessage(session);
        if (fromname == null || fromname.isEmpty()) {
            message.setFrom(new InternetAddress(from));
        } else {
            message.setFrom(new InternetAddress(from, fromname));
        }
        message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setContent(msg, "text/html");
        //Transport.send(message);
        transport.setLocalHost("REMOTE-CLIENT");
        transport.connect();
        transport.sendMessage(message, rcptto);

    } catch (Exception e) {
        e.printStackTrace();
        ok = false;
    } finally {

        try {
            if (!ok) {
                response = "SENDING FAILED:" + transport.getLastServerResponse();
            } else {
                response = "SENDING SUCCESS:" + transport.getLastServerResponse();
            }

            transport.close();

        } catch (Exception f) {

        }

    }
    return response;
}

From source file:it.infn.ct.nuclemd.Nuclemd.java

private void sendHTMLEmail(String USERNAME, String TO, String FROM, String SMTP_HOST, String ApplicationAcronym,
        String GATEWAY) {//from   w  w  w. java  2  s  .c o m

    log.info("\n- Sending email notification to the user " + USERNAME + " [ " + TO + " ]");

    log.info("\n- SMTP Server = " + SMTP_HOST);
    log.info("\n- Sender = " + FROM);
    log.info("\n- Receiver = " + TO);
    log.info("\n- Application = " + ApplicationAcronym);
    log.info("\n- Gateway = " + GATEWAY);

    // Assuming you are sending email from localhost
    String HOST = "localhost";

    // Get system properties
    Properties properties = System.getProperties();
    properties.setProperty(SMTP_HOST, HOST);

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(FROM));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        //message.addRecipient(Message.RecipientType.CC, new InternetAddress(FROM));

        // Set Subject: header field
        message.setSubject(" [liferay-sg-gateway] - [ " + GATEWAY + " ] ");

        Date currentDate = new Date();
        currentDate.setTime(currentDate.getTime());

        // Send the actual HTML message, as big as you like
        message.setContent("<br/><H4>"
                + "<img src=\"http://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc6/195775_220075701389624_155250493_n.jpg\" width=\"100\">Science Gateway Notification"
                + "</H4><hr><br/>" + "<b>Description:</b> Notification for the application <b>[ "
                + ApplicationAcronym + " ]</b><br/><br/>"
                + "<i>The application has been successfully submitted from the [ " + GATEWAY
                + " ]</i><br/><br/>" + "<b>TimeStamp:</b> " + currentDate + "<br/><br/>"
                + "<b>Disclaimer:</b><br/>"
                + "<i>This is an automatic message sent by the Science Gateway based on Liferay technology.<br/>"
                + "If you did not submit any jobs through the Science Gateway, please " + "<a href=\"mailto:"
                + FROM + "\">contact us</a></i>", "text/html");

        // Send message
        Transport.send(message);
    } catch (MessagingException ex) {
        Logger.getLogger(Nuclemd.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:it.infn.ct.wrf.Wrf.java

private void sendHTMLEmail(String USERNAME, String TO, String FROM, String SMTP_HOST, String ApplicationAcronym,
        String GATEWAY) {// w w  w  .j  av a2s  .  c  o  m

    log.info("\n- Sending email notification to the user " + USERNAME + " [ " + TO + " ]");

    log.info("\n- SMTP Server = " + SMTP_HOST);
    log.info("\n- Sender = " + FROM);
    log.info("\n- Receiver = " + TO);
    log.info("\n- Application = " + ApplicationAcronym);
    log.info("\n- Gateway = " + GATEWAY);

    // Assuming you are sending email from localhost
    String HOST = "localhost";

    // Get system properties
    Properties properties = System.getProperties();
    properties.setProperty(SMTP_HOST, HOST);

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(FROM));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        //message.addRecipient(Message.RecipientType.CC, new InternetAddress(FROM));

        // Set Subject: header field
        message.setSubject(" [liferay-sg-gateway] - [ " + GATEWAY + " ] ");

        Date currentDate = new Date();
        currentDate.setTime(currentDate.getTime());

        // Send the actual HTML message, as big as you like
        message.setContent("<br/><H4>"
                + "<img src=\"http://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc6/195775_220075701389624_155250493_n.jpg\" width=\"100\">Science Gateway Notification"
                + "</H4><hr><br/>" + "<b>Description:</b> Notification for the application <b>[ "
                + ApplicationAcronym + " ]</b><br/><br/>"
                + "<i>The application has been successfully submitted from the [ " + GATEWAY
                + " ]</i><br/><br/>" + "<b>TimeStamp:</b> " + currentDate + "<br/><br/>"
                + "<b>Disclaimer:</b><br/>"
                + "<i>This is an automatic message sent by the Science Gateway based on Liferay technology.<br/>"
                + "If you did not submit any jobs through the Science Gateway, please " + "<a href=\"mailto:"
                + FROM + "\">contact us</a></i>", "text/html");

        // Send message
        Transport.send(message);
    } catch (MessagingException mex) {
        mex.printStackTrace();
    }
}

From source file:org.jasig.ssp.service.impl.MessageServiceImpl.java

@Override
@Transactional(readOnly = false)/*from ww  w.  j a va2 s .com*/
public boolean sendMessage(@NotNull final Message message)
        throws ObjectNotFoundException, SendFailedException, UnsupportedEncodingException {

    LOGGER.info("BEGIN : sendMessage()");
    LOGGER.info(addMessageIdToError(message) + "Sending message: {}", message.toString());

    try {
        final MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        final MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);

        // process FROM addresses
        InternetAddress from;
        String appName = configService.getByName("app_title").getValue();

        //We used the configured outbound email address for every outgoing message
        //If a message was initiated by an end user, their name will be attached to the 'from' while
        //the configured outbound address will be the actual address used for example "Amy Aministrator (SSP) <myconfiguredaddress@foobar.com>"
        String name = appName + " Administrator";
        if (message.getSender() != null && !message.getSender().getEmailAddresses().isEmpty()
                && !message.getSender().getId().equals(Person.SYSTEM_ADMINISTRATOR_ID)) {
            InternetAddress[] froms = getEmailAddresses(message.getSender(), "from:", message.getId());
            if (froms.length > 0) {
                name = message.getSender().getFullName() + " (" + appName + ")";
            }
        }

        from = new InternetAddress(configService.getByName("outbound_email_address").getValue(), name);
        if (!this.validateEmail(from.getAddress())) {
            throw new AddressException("Invalid from: email address [" + from.getAddress() + "]");
        }

        mimeMessageHelper.setFrom(from);
        message.setSentFromAddress(from.toString());
        mimeMessageHelper.setReplyTo(from);
        message.setSentReplyToAddress(from.toString());

        // process TO addresses
        InternetAddress[] tos = null;
        if (message.getRecipient() != null && message.getRecipient().hasEmailAddresses()) { // NOPMD by jon.adams         
            tos = getEmailAddresses(message.getRecipient(), "to:", message.getId());
        } else {
            tos = getEmailAddresses(message.getRecipientEmailAddress(), "to:", message.getId());
        }
        if (tos.length > 0) {
            mimeMessageHelper.setTo(tos);
            message.setSentToAddresses(StringUtils.join(tos, ",").trim());
        } else {
            StringBuilder errorMsg = new StringBuilder();

            errorMsg.append(addMessageIdToError(message) + " Message " + message.toString()
                    + " could not be sent. No valid recipient email address found: '");

            if (message.getRecipient() != null) {
                errorMsg.append(message.getRecipient().getPrimaryEmailAddress());
            } else {
                errorMsg.append(message.getRecipientEmailAddress());
            }
            LOGGER.error(errorMsg.toString());
            throw new MessagingException(errorMsg.toString());
        }

        // process BCC addresses
        try {
            InternetAddress[] bccs = getEmailAddresses(getBcc(), "bcc:", message.getId());
            if (bccs.length > 0) {
                mimeMessageHelper.setBcc(bccs);
                message.setSentBccAddresses(StringUtils.join(bccs, ",").trim());
            }
        } catch (Exception exp) {
            LOGGER.warn("Unrecoverable errors were generated adding carbon copy to message: " + message.getId()
                    + "Attempt to send message still initiated.", exp);
        }

        // process CC addresses
        try {
            InternetAddress[] carbonCopies = getEmailAddresses(message.getCarbonCopy(), "cc:", message.getId());
            if (carbonCopies.length > 0) {
                mimeMessageHelper.setCc(carbonCopies);
                message.setSentCcAddresses(StringUtils.join(carbonCopies, ",").trim());
            }
        } catch (Exception exp) {
            LOGGER.warn("Unrecoverable errors were generated adding bcc to message: " + message.getId()
                    + "Attempt to send message still initiated.", exp);
        }

        mimeMessageHelper.setSubject(message.getSubject());
        mimeMessageHelper.setText(message.getBody());
        mimeMessage.setContent(message.getBody(), "text/html");

        send(mimeMessage);

        message.setSentDate(new Date());
        messageDao.save(message);
    } catch (final MessagingException e) {
        LOGGER.error("ERROR : sendMessage() : {}", e);
        handleSendMessageError(message);
        throw new SendFailedException(addMessageIdToError(message) + "The message parameters were invalid.", e);
    }

    LOGGER.info("END : sendMessage()");
    return true;
}