Example usage for javax.mail.internet MimeMessage setText

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

Introduction

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

Prototype

@Override
public void setText(String text) throws MessagingException 

Source Link

Document

Convenience method that sets the given String as this part's content, with a MIME type of "text/plain".

Usage

From source file:com.buzzdavidson.spork.client.OWAClient.java

/**
 * Fetch the body of the email message given a message URL.
 *
 * @param message Mime message to add body to
 * @param messageUrl URL of message (OWA WebDav)
 *///from   w ww  . j a va  2  s .  c om
private void populateMessage(MimeMessage message, String messageUrl) {
    GetMethod get = new GetMethod(messageUrl);
    get.setRequestHeader("Translate", "F");
    try {
        logger.info("Requesting message body via url [" + messageUrl + "]");
        int status = client.executeMethod(get);
        if (logger.isDebugEnabled()) {
            logger.debug("Message request returned status code [" + status + "]");
        }
        if (status == HttpStatus.SC_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream()));
            String contentType = OWAUtils.getSingleHeader(message, PARAM_CONTENT_TYPE);
            String contentEncoding = OWAUtils.getSingleHeader(message, PARAM_CONTENT_ENCODING);
            boolean needContentType = (contentType == null || contentType.length() < 1);

            // first set of entries are headers, followed by empty line.  skip to first empty line.
            for (String line; (line = in.readLine()) != null;) {
                if (line != null && line.trim().length() == 0) {
                    break;
                }
            }

            StringBuffer buf = new StringBuffer();
            for (String line; (line = in.readLine()) != null;) {
                buf.append(line);
                buf.append(NEWLINE);
            }

            if (needContentType || contentType.contains(CONTENT_TYPE_TEXT_PLAIN)) {
                // OWA sometimes reports XML or HTML content as "text/plain"; check for this.

                if (logger.isDebugEnabled()) {
                    logger.debug("checking content encoding");
                }
                byte[] blob = buf.toString().getBytes();
                if (logger.isDebugEnabled()) {
                    logger.debug("blob length is " + blob.length + " bytes");
                }
                if (contentEncoding.equals(BASE_64_ENCODING)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("blob is base64 encoded, decoding");
                    }
                    byte[] newblob = Base64.decodeBase64(blob);
                    if (logger.isDebugEnabled()) {
                        logger.debug("decoded blob length is " + newblob.length + " bytes");
                    }
                    String data = new String(newblob);
                    buf = new StringBuffer(data);
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("blob is encoded with [" + contentEncoding + "], not decoding");
                    }
                }
                contentType = determineContentType(buf, message);
            }

            if (wantDiagnostics) {
                buf.append(NEWLINE);
                buf.append("-------------------------------------");
                buf.append(NEWLINE);
                buf.append("SPORK Data");
                buf.append(NEWLINE);
                buf.append("content-encoding: " + contentEncoding);
                buf.append(NEWLINE);
                buf.append("content-type: " + contentType);
                if (needContentType) {
                    buf.append(" (calculated) " + contentType);
                    buf.append(" Message processed "
                            + DateFormat.getDateInstance(DateFormat.SHORT).format(new Date()));
                }
            }

            if (needContentType) {
                buf = cleanupBuffer(buf);
            }

            buf.append(NEWLINE);
            message.setText(buf.toString());
            int len = buf.length();
            message.setHeader(PARAM_CONTENT_LENGTH, Integer.valueOf(len).toString()); // close enough :)
            if (contentType != null && contentType.length() > 0) {
                message.setHeader(PARAM_CONTENT_TYPE, contentType);
            }
            message.saveChanges();
        }
    } catch (HttpException ex) {
        logger.error("Received HttpException fetching message body", ex);
    } catch (UnsupportedEncodingException ex) {
        logger.error("Received UnsupportedEncodingException fetching message body", ex);
    } catch (IOException ex) {
        logger.error("Received IOException fetching message body", ex);
    } catch (MessagingException ex) {
        logger.error("Received MessagingException fetching message body", ex);
    }
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * @inheritDoc// ww w.j a v a  2  s  .  com
 */
@Override
protected byte[] getContent(ExchangeSession.Message message) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream contentInputStream;
    try {
        try {
            try {
                contentInputStream = getContentInputStream(message.messageUrl);
            } catch (UnknownHostException e) {
                // failover for misconfigured Exchange server, replace host name in url
                restoreHostName = true;
                contentInputStream = getContentInputStream(message.messageUrl);
            }
        } catch (HttpNotFoundException e) {
            LOGGER.debug("Message not found at: " + message.messageUrl + ", retrying with permanenturl");
            contentInputStream = getContentInputStream(message.permanentUrl);
        }

        try {
            IOUtil.write(contentInputStream, baos);
        } finally {
            contentInputStream.close();
        }

    } catch (LoginTimeoutException e) {
        // throw error on expired session
        LOGGER.warn(e.getMessage());
        throw e;
    } catch (IOException e) {
        LOGGER.warn("Broken message at: " + message.messageUrl + " permanentUrl: " + message.permanentUrl
                + ", trying to rebuild from properties");

        try {
            DavPropertyNameSet messageProperties = new DavPropertyNameSet();
            messageProperties.add(Field.getPropertyName("contentclass"));
            messageProperties.add(Field.getPropertyName("message-id"));
            messageProperties.add(Field.getPropertyName("from"));
            messageProperties.add(Field.getPropertyName("to"));
            messageProperties.add(Field.getPropertyName("cc"));
            messageProperties.add(Field.getPropertyName("subject"));
            messageProperties.add(Field.getPropertyName("date"));
            messageProperties.add(Field.getPropertyName("htmldescription"));
            messageProperties.add(Field.getPropertyName("body"));
            PropFindMethod propFindMethod = new PropFindMethod(encodeAndFixUrl(message.permanentUrl),
                    messageProperties, 0);
            DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod);
            MultiStatus responses = propFindMethod.getResponseBodyAsMultiStatus();
            if (responses.getResponses().length > 0) {
                MimeMessage mimeMessage = new MimeMessage((Session) null);

                DavPropertySet properties = responses.getResponses()[0].getProperties(HttpStatus.SC_OK);
                String propertyValue = getPropertyIfExists(properties, "contentclass");
                if (propertyValue != null) {
                    mimeMessage.addHeader("Content-class", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "date");
                if (propertyValue != null) {
                    mimeMessage.setSentDate(parseDateFromExchange(propertyValue));
                }
                propertyValue = getPropertyIfExists(properties, "from");
                if (propertyValue != null) {
                    mimeMessage.addHeader("From", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "to");
                if (propertyValue != null) {
                    mimeMessage.addHeader("To", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "cc");
                if (propertyValue != null) {
                    mimeMessage.addHeader("Cc", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "subject");
                if (propertyValue != null) {
                    mimeMessage.setSubject(propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "htmldescription");
                if (propertyValue != null) {
                    mimeMessage.setContent(propertyValue, "text/html; charset=UTF-8");
                } else {
                    propertyValue = getPropertyIfExists(properties, "body");
                    if (propertyValue != null) {
                        mimeMessage.setText(propertyValue);
                    }
                }
                mimeMessage.writeTo(baos);
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray()));
            }
        } catch (IOException e2) {
            LOGGER.warn(e2);
        } catch (DavException e2) {
            LOGGER.warn(e2);
        } catch (MessagingException e2) {
            LOGGER.warn(e2);
        }
        // other exception
        if (baos.size() == 0 && Settings.getBooleanProperty("davmail.deleteBroken")) {
            LOGGER.warn("Deleting broken message at: " + message.messageUrl + " permanentUrl: "
                    + message.permanentUrl);
            try {
                message.delete();
            } catch (IOException ioe) {
                LOGGER.warn("Unable to delete broken message at: " + message.permanentUrl);
            }
            throw e;
        }
    }

    return baos.toByteArray();
}

From source file:library.Form_Library.java

License:asdf

public void sendFromGMail(String from, String pass, String to, String subject, String body) {
    this.taBaoCao.append("Sent to " + to + " successfully.\n");
    Properties props = System.getProperties();
    String host = "smtp.gmail.com";
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");

    Session session = Session.getDefaultInstance(props);
    MimeMessage message = new MimeMessage(session);

    try {/*from w w w  .  j av  a2 s  .  co m*/
        message.setFrom(new InternetAddress(from));
        InternetAddress toAddress = new InternetAddress();

        // To get the array of addresses
        //            for( int i = 0; i < to.length; i++ ) {
        toAddress = new InternetAddress(to);
        //            }

        //            for( int i = 0; i < toAddress.length; i++) {
        message.addRecipient(Message.RecipientType.TO, toAddress);
        //            }

        message.setSubject(subject);
        message.setText(body);
        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);

        transport.sendMessage(message, message.getAllRecipients());

        System.out.print("Successfully Sent" + "\n");
        transport.close();
    } catch (AddressException ae) {
        ae.printStackTrace();
    } catch (MessagingException me) {
        me.printStackTrace();
    }
}

From source file:com.riq.MailHandlerServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)

        throws IOException {

    log.info("Inside MailServlet doPost");

    // TODO get path information to determine target Department for this email

    PersistenceManager pm = PMF.get().getPersistenceManager();
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    try {/*from   w w  w.ja  v  a  2s  .c om*/

        MimeMessage msg = new MimeMessage(session, req.getInputStream());
        Address sender = msg.getFrom()[0];
        Address replyTo = msg.getReplyTo()[0];

        //      DEBUG
        //       log.info("Message Class: " + msg.getClass());
        //       log.info("Message Stream: " + msg.getInputStream());
        //       log.info("Message RawStream: " + msg.getRawInputStream());
        //       log.info("Message Flags: " + msg.getFlags());
        //       log.info("Message Content: " + msg.getContent().toString());
        //       log.info("Message ContentID: " + msg.getContentID());
        //       log.info("Message ContentMD: " + msg.getContentMD5());
        //       log.info("Message ContentType: " + msg.getContentType());
        //       log.info("Message Description: " + msg.getDescription());
        //       log.info("Message Disposition: " + msg.getDisposition());
        //       log.info("Message Encoding: " + msg.getEncoding());
        //       log.info("Message Filename: " + msg.getFileName());
        //       log.info("Message Line Count: " + msg.getLineCount());
        //       log.info("Message ID: " + msg.getMessageID());
        //       log.info("Message Number: " + msg.getMessageNumber());
        //       log.info("Message Size: " + msg.getSize());
        //       log.info("Message Subject: " + msg.getSubject());
        //       log.info("Message RawInputStream: " + msg.getRawInputStream().toString());
        //       log.info("Message ReplyTo: " + replyTo);
        //       log.info("Message Sender: " + sender.toString());
        //       log.info("Request URL TO: " +  getServletContext());      

        String alertMsgString = getText(msg);

        alertMsgString = alertMsgString.replaceAll("Begin forwarded message:", "");
        alertMsgString = alertMsgString.replaceAll("Forwarded message", "");
        alertMsgString = alertMsgString.replaceAll("Dispatch@co.morris.nj.us", "");
        alertMsgString = alertMsgString.replaceAll("Date:", "");
        alertMsgString = alertMsgString.replaceAll(">", "");
        alertMsgString = alertMsgString.replaceAll("::", "-");
        alertMsgString = alertMsgString.replaceAll("< ", "");
        alertMsgString = alertMsgString.replaceAll("----------", "");
        alertMsgString = alertMsgString.replaceAll("Subject:", "");
        alertMsgString = alertMsgString.replaceAll("To:", "");
        alertMsgString = alertMsgString.replaceAll("From:", "");

        //  Added to grab gmail confirmations
        //  alertMsgString = alertMsgString.substring(50, 300);

        try {

            String queryDept = "select from " + Department.class.getName() +
            // TODO: johnreilly workaround for getting allRecipients... 
            // " where dispatchId == '" + toAddressDigitsOnly + "' " + 
                    " where dispatchId == '2599' " + " && fromEmail == '" + sender + "' ";
            log.info("queryDept: " + queryDept);
            List<Department> depts = (List<Department>) pm.newQuery(queryDept).execute();

            if (depts.size() != 0) {

                for (Department d : depts) {

                    // need to filter further e.g. last two hours
                    String queryAlert = "select from " + Alert.class.getName() + " where deptId == "
                            + depts.get(0).getid() + " && messageId == '" + msg.getMessageID() + "' ";
                    log.info("queryAlert: " + queryAlert);
                    List<Alert> alerts = (List<Alert>) pm.newQuery(queryAlert).execute();
                    log.info("queryAlert Result Qty: " + alerts.size());

                    if (alerts.size() == 0) {

                        riqGeocode(alertMsgString);

                        // geocode the address from the Alert
                        Map<String, String> geoResults = riqGeocode(alertMsgString);
                        log.info("lat print: " + geoResults.get("lat"));
                        log.info("lng print: " + geoResults.get("lng"));

                        // create the alert
                        Long deptId = depts.get(0).getid();
                        Long timeStamp = System.currentTimeMillis();
                        Alert a = new Alert(deptId, timeStamp, alertMsgString.trim(), sender.toString(),
                                "Active", "", geoResults.get("lat"), geoResults.get("lng"), msg.getMessageID());
                        pm.makePersistent(a);

                        // query to get id of this alert
                        String queryThisAlert = "select from " + Alert.class.getName() + " where deptId == "
                                + deptId + " " + " && timeStamp == " + timeStamp;
                        log.info("queryThisAlert: " + queryThisAlert);
                        List<Alert> thisAlert = (List<Alert>) pm.newQuery(queryThisAlert).execute();
                        log.info("queryCurrentAlert Result Qty: " + thisAlert.size());

                        // create Tracking records for "special" Locations
                        String querySpecialLocs = "select from " + Location.class.getName()
                                + " where special == 'yes' && deptId == " + deptId;
                        log.info("querySpecialLocs: " + querySpecialLocs);
                        List<Location> specialLocs = (List<Location>) pm.newQuery(querySpecialLocs).execute();
                        log.info("querySpecialLocs qty: " + specialLocs.size());

                        for (Location specL : specialLocs) {
                            Tracking tSL = new Tracking(deptId, thisAlert.get(0).getid(), specL.getid(),
                                    System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd
                                    "location", specL.getid(), null, "autoAddLocation");
                            pm.makePersistent(tSL);
                        }

                        // search Dept for Location where distant Members presumed not to be responding are set
                        String queryFarawayLocs = "select from " + Location.class.getName()
                                + " where vru == '2' && deptId == " + deptId;
                        log.info("querySpecialLocs: " + queryFarawayLocs);
                        List<Location> farawayLoc = (List<Location>) pm.newQuery(queryFarawayLocs).execute();
                        log.info("queryFarawayLocs qty: " + farawayLoc.size());

                        // create Tracking records for Members presumed not to be responder due to fresh ETA
                        String queryFarAwayResponders = "select from " + Member.class.getName()
                                + " where distGroup == '4' ";
                        log.info("queryFarAwayResponders: " + queryFarAwayResponders);
                        List<Member> farawayMembers = (List<Member>) pm.newQuery(queryFarAwayResponders)
                                .execute();
                        log.info("queryFarAwayResponders qty: " + farawayMembers.size());

                        if (farawayMembers.size() != 0) {
                            for (Member far : farawayMembers) {
                                Tracking tMFAR = new Tracking(deptId, thisAlert.get(0).getid(),
                                        farawayLoc.get(0).getid(), System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd
                                        "farawayAddMember", far.getid(), null, responseType);
                                pm.makePersistent(tMFAR);
                            }
                        }

                        // TODO: testing restriction HACKER - remove at launch
                        // send alert email
                        String queryMember = "select from " + Member.class.getName() + " where deptId == "
                                + deptId + " && type == 'Hacker' ";
                        List<Member> members = (List<Member>) pm.newQuery(queryMember).execute();

                        //TODO Geocode address to insure easy navigation
                        //TODO johnreilly: add street and town fields to Alert
                        msg.setFrom(
                                new InternetAddress("admin@responderiq05.appspotmail.com", "FirstResponder"));
                        msg.setSubject("Alert!");
                        msg.setText(" Y=" + d.getinboundVRU1() + "&N=" + d.getinboundVRU2() +
                        // "&3=" + d.getinboundVRU3() +  
                                "&A=" + thisAlert.get(0).getalertMsgString());

                        // send message to all dept members who permit tracking (and sending email alerts)
                        for (Member m : members) {
                            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m.getsmsAddress(),
                                    m.getfirstName() + "" + m.getlastName()));
                            log.info("Member: " + m.getsmsAddress() + "|" + m.getlastName());
                        }
                    }
                    // only process for one department - should only be one department
                    break;
                }
            }
        } catch (MessagingException me) {
            log.info("Error: Messaging");
        } catch (IndexOutOfBoundsException mi) {
            log.info("Error: Out of Bounds");
        }

        // Do not send alert notification if email is a Google Confirmation
        //      if (! sender.toString().contains("mail-noreply@google.com")) {
        //        Transport.send(msg);
        //      }

    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    } finally {
        pm.close();
    }

}

From source file:com.sonicle.webtop.mail.Service.java

public Message createMessage(String from, SimpleMessage smsg, List<JsAttachment> attachments, boolean tosave)
        throws Exception {
    MimeMessage msg = null;
    boolean success = true;

    String[] to = SimpleMessage.breakAddr(smsg.getTo());
    String[] cc = SimpleMessage.breakAddr(smsg.getCc());
    String[] bcc = SimpleMessage.breakAddr(smsg.getBcc());
    String replyTo = smsg.getReplyTo();

    msg = new MimeMessage(mainAccount.getMailSession());
    msg.setFrom(getInternetAddress(from));
    InternetAddress ia = null;/*from   ww w .j  av a  2  s . c  om*/

    //set the TO recipient
    for (int q = 0; q < to.length; q++) {
        //        Service.logger.debug("to["+q+"]="+to[q]);
        to[q] = to[q].replace(',', ' ');
        try {
            ia = getInternetAddress(to[q]);
        } catch (AddressException exc) {
            throw new AddressException(to[q]);
        }
        msg.addRecipient(Message.RecipientType.TO, ia);
    }

    //set the CC recipient
    for (int q = 0; q < cc.length; q++) {
        cc[q] = cc[q].replace(',', ' ');
        try {
            ia = getInternetAddress(cc[q]);
        } catch (AddressException exc) {
            throw new AddressException(cc[q]);
        }
        msg.addRecipient(Message.RecipientType.CC, ia);
    }

    //set BCC recipients
    for (int q = 0; q < bcc.length; q++) {
        bcc[q] = bcc[q].replace(',', ' ');
        try {
            ia = getInternetAddress(bcc[q]);
        } catch (AddressException exc) {
            throw new AddressException(bcc[q]);
        }
        msg.addRecipient(Message.RecipientType.BCC, ia);
    }

    //set reply to addr
    if (replyTo != null && replyTo.length() > 0) {
        Address[] replyaddr = new Address[1];
        replyaddr[0] = getInternetAddress(replyTo);
        msg.setReplyTo(replyaddr);
    }

    //add any header
    String headerLines[] = smsg.getHeaderLines();
    for (int i = 0; i < headerLines.length; ++i) {
        if (!headerLines[i].startsWith("Sonicle-reply-folder")) {
            msg.addHeaderLine(headerLines[i]);
        }
    }

    //add reply/references
    String inreplyto = smsg.getInReplyTo();
    String references[] = smsg.getReferences();
    String replyfolder = smsg.getReplyFolder();
    if (inreplyto != null) {
        msg.setHeader("In-Reply-To", inreplyto);
    }
    if (references != null && references[0] != null) {
        msg.setHeader("References", references[0]);
    }
    if (tosave) {
        if (replyfolder != null) {
            msg.setHeader("Sonicle-reply-folder", replyfolder);
        }
        msg.setHeader("Sonicle-draft", "true");
    }

    //add forward data
    String forwardedfrom = smsg.getForwardedFrom();
    String forwardedfolder = smsg.getForwardedFolder();
    if (forwardedfrom != null) {
        msg.setHeader("Forwarded-From", forwardedfrom);
    }
    if (tosave) {
        if (forwardedfolder != null) {
            msg.setHeader("Sonicle-forwarded-folder", forwardedfolder);
        }
        msg.setHeader("Sonicle-draft", "true");
    }
    //set the subject
    String subject = smsg.getSubject();
    try {
        //subject=MimeUtility.encodeText(smsg.getSubject(), "ISO-8859-1", null);
        subject = MimeUtility.encodeText(smsg.getSubject());
    } catch (Exception exc) {
    }
    msg.setSubject(subject);

    //set priority
    int priority = smsg.getPriority();
    if (priority != 3) {
        msg.setHeader("X-Priority", "" + priority);

        //set receipt
    }
    String receiptTo = from;
    try {
        receiptTo = MimeUtility.encodeText(from, "ISO-8859-1", null);
    } catch (Exception exc) {
    }
    if (smsg.getReceipt()) {
        msg.setHeader("Disposition-Notification-To", from);

        //see if there are any new attachments for the message
    }
    int noAttach;
    int newAttach;

    if (attachments == null) {
        newAttach = 0;
    } else {
        newAttach = attachments.size();
    }

    //get the array of the old attachments
    Part[] oldParts = smsg.getAttachments();

    //check if there are old attachments
    if (oldParts == null) {
        noAttach = 0;
    } else { //old attachments exist
        noAttach = oldParts.length;
    }

    if ((newAttach > 0) || (noAttach > 0) || !smsg.getMime().equalsIgnoreCase("text/plain")) {
        // create the main Multipart
        MimeMultipart mp = new MimeMultipart("mixed");
        MimeMultipart unrelated = null;

        String textcontent = smsg.getTextContent();
        //if is text, or no alternative text is available, add the content as one single body part
        //else create a multipart/alternative with both rich and text mime content
        if (textcontent == null || smsg.getMime().equalsIgnoreCase("text/plain")) {
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8"));
            mp.addBodyPart(mbp1);
        } else {
            MimeMultipart alternative = new MimeMultipart("alternative");
            //the rich part
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8"));
            //the text part
            MimeBodyPart mbp1 = new MimeBodyPart();

            /*          ByteArrayOutputStream bos=new ByteArrayOutputStream(textcontent.length());
             com.sun.mail.util.QPEncoderStream qpe=new com.sun.mail.util.QPEncoderStream(bos);
             for(int i=0;i<textcontent.length();++i) {
             try {
             qpe.write(textcontent.charAt(i));
             } catch(IOException exc) {
             Service.logger.error("Exception",exc);
             }
             }
             textcontent=new String(bos.toByteArray());*/
            mbp1.setContent(textcontent, MailUtils.buildPartContentType("text/plain", "UTF-8"));
            //          mbp1.setHeader("Content-transfer-encoding","quoted-printable");

            alternative.addBodyPart(mbp1);
            alternative.addBodyPart(mbp2);

            MimeBodyPart altbody = new MimeBodyPart();
            altbody.setContent(alternative);

            mp.addBodyPart(altbody);
        }

        if (noAttach > 0) { //if there are old attachments
            // create the parts with the attachments
            //MimeBodyPart[] mbps2 = new MimeBodyPart[noAttach];
            //Part[] mbps2 = new Part[noAttach];

            //for(int e = 0;e < noAttach;e++) {
            //  mbps2[e] = (Part)oldParts[e];
            //}//end for e
            //add the old attachment parts
            for (int r = 0; r < noAttach; r++) {
                Object content = null;
                String contentType = null;
                String contentFileName = null;
                if (oldParts[r] instanceof Message) {
                    //                Service.logger.debug("Attachment is a message");
                    Message msgpart = (Message) oldParts[r];
                    MimeMessage mm = new MimeMessage(mainAccount.getMailSession());
                    mm.addFrom(msgpart.getFrom());
                    mm.setRecipients(Message.RecipientType.TO, msgpart.getRecipients(Message.RecipientType.TO));
                    mm.setRecipients(Message.RecipientType.CC, msgpart.getRecipients(Message.RecipientType.CC));
                    mm.setRecipients(Message.RecipientType.BCC,
                            msgpart.getRecipients(Message.RecipientType.BCC));
                    mm.setReplyTo(msgpart.getReplyTo());
                    mm.setSentDate(msgpart.getSentDate());
                    mm.setSubject(msgpart.getSubject());
                    mm.setContent(msgpart.getContent(), msgpart.getContentType());
                    content = mm;
                    contentType = "message/rfc822";
                } else {
                    //                Service.logger.debug("Attachment is not a message");
                    content = oldParts[r].getContent();
                    if (!(content instanceof MimeMultipart)) {
                        contentType = oldParts[r].getContentType();
                        contentFileName = oldParts[r].getFileName();
                    }
                }
                MimeBodyPart mbp = new MimeBodyPart();
                if (contentFileName != null) {
                    mbp.setFileName(contentFileName);
                    //              Service.logger.debug("adding attachment mime "+contentType+" filename "+contentFileName);
                    contentType += "; name=\"" + contentFileName + "\"";
                }
                if (content instanceof MimeMultipart)
                    mbp.setContent((MimeMultipart) content);
                else
                    mbp.setDataHandler(new DataHandler(content, contentType));
                mp.addBodyPart(mbp);
            }

        } //end if, adding old attachments

        if (newAttach > 0) { //if there are new attachments
            // create the parts with the attachments
            MimeBodyPart[] mbps = new MimeBodyPart[newAttach];

            for (int e = 0; e < newAttach; e++) {
                mbps[e] = new MimeBodyPart();

                // attach the file to the message
                JsAttachment attach = (JsAttachment) attachments.get(e);
                UploadedFile upfile = getUploadedFile(attach.uploadId);
                FileDataSource fds = new FileDataSource(upfile.getFile());
                mbps[e].setDataHandler(new DataHandler(fds));
                // filename starts has format:
                // "_" + userid + sessionId + "_" + filename
                //
                if (attach.inline) {
                    mbps[e].setDisposition(Part.INLINE);
                }
                String contentFileName = attach.fileName.trim();
                mbps[e].setFileName(contentFileName);
                String contentType = upfile.getMediaType() + "; name=\"" + contentFileName + "\"";
                mbps[e].setHeader("Content-type", contentType);
                if (attach.cid != null && attach.cid.trim().length() > 0) {
                    mbps[e].setHeader("Content-ID", "<" + attach.cid + ">");
                    mbps[e].setHeader("X-Attachment-Id", attach.cid);
                    mbps[e].setDisposition(Part.INLINE);
                    if (unrelated == null)
                        unrelated = new MimeMultipart("mixed");
                }
            } //end for e

            //add the new attachment parts
            if (unrelated == null) {
                for (int r = 0; r < newAttach; r++)
                    mp.addBodyPart(mbps[r]);
            } else {
                //mp becomes the related part with text parts and cids
                MimeMultipart related = mp;
                related.setSubType("related");
                //nest the related part into the mixed part
                mp = unrelated;
                MimeBodyPart mbd = new MimeBodyPart();
                mbd.setContent(related);
                mp.addBodyPart(mbd);
                for (int r = 0; r < newAttach; r++) {
                    if (mbps[r].getHeader("Content-ID") != null) {
                        related.addBodyPart(mbps[r]);
                    } else {
                        mp.addBodyPart(mbps[r]);
                    }
                }
            }

        } //end if, adding new attachments

        //
        //          msg.addHeaderLine("This is a multi-part message in MIME format.");
        // add the Multipart to the message
        msg.setContent(mp);

    } else { //end if newattach
        msg.setText(smsg.getContent());
    } //singlepart message

    msg.setSentDate(new java.util.Date());

    return msg;

}