Example usage for javax.mail.internet MimeMessage addRecipient

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

Introduction

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

Prototype

public void addRecipient(RecipientType type, Address address) throws MessagingException 

Source Link

Document

Add this recipient address to the existing ones of the given type.

Usage

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;// w  w  w .  ja v a 2s.co 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.wrf.Wrf.java

private void sendHTMLEmail(String USERNAME, String TO, String FROM, String SMTP_HOST, String ApplicationAcronym,
        String GATEWAY) {/*from   w ww . j  ava  2s  . com*/

    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:davmail.exchange.ExchangeSession.java

/**
 * Send message in reader to recipients.
 * Detect visible recipients in message body to determine bcc recipients
 *
 * @param rcptToRecipients recipients list
 * @param mimeMessage      mime message/*w w  w.jav  a  2  s.c  o m*/
 * @throws IOException        on error
 * @throws MessagingException on error
 */
public void sendMessage(List<String> rcptToRecipients, MimeMessage mimeMessage)
        throws IOException, MessagingException {
    // detect duplicate send command
    String messageId = mimeMessage.getMessageID();
    if (lastSentMessageId != null && lastSentMessageId.equals(messageId)) {
        LOGGER.debug("Dropping message id " + messageId + ": already sent");
        return;
    }
    lastSentMessageId = messageId;

    convertResentHeader(mimeMessage, "From");
    convertResentHeader(mimeMessage, "To");
    convertResentHeader(mimeMessage, "Cc");
    convertResentHeader(mimeMessage, "Bcc");
    convertResentHeader(mimeMessage, "Message-Id");

    mimeMessage.removeHeader("From");

    // remove visible recipients from list
    Set<String> visibleRecipients = new HashSet<String>();
    List<InternetAddress> recipients = getAllRecipients(mimeMessage);
    for (InternetAddress address : recipients) {
        visibleRecipients.add((address.getAddress().toLowerCase()));
    }
    for (String recipient : rcptToRecipients) {
        if (!visibleRecipients.contains(recipient.toLowerCase())) {
            mimeMessage.addRecipient(javax.mail.Message.RecipientType.BCC, new InternetAddress(recipient));
        }
    }
    sendMessage(mimeMessage);

}

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 {//w ww  . ja  va 2 s  .c o  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.sonicle.webtop.mail.Service.java

public boolean sendMsg(Identity ident, InternetAddress from, Collection<InternetAddress> to,
        Collection<InternetAddress> cc, Collection<InternetAddress> bcc, String subject, MimeMultipart part) {

    try {/*  w  w  w.java 2  s.co  m*/
        subject = MimeUtility.encodeText(subject);
    } catch (Exception ex) {
    }

    try {
        MailAccount account = getAccount(ident);

        MimeMessage message = new MimeMessage(account.getMailSession());
        message.setSubject(subject);
        message.addFrom(new InternetAddress[] { from });

        if (to != null) {
            for (InternetAddress ia : to)
                message.addRecipient(Message.RecipientType.TO, ia);
        }
        if (cc != null) {
            for (InternetAddress ia : cc)
                message.addRecipient(Message.RecipientType.CC, ia);
        }
        if (bcc != null) {
            for (InternetAddress ia : bcc)
                message.addRecipient(Message.RecipientType.BCC, ia);
        }

        message.setContent(part);
        message.setSentDate(new java.util.Date());

        return sendMsg(ident, message);

    } catch (MessagingException ex) {
        logger.warn("Unable to send message", ex);
        return false;
    }
}

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 {/*www.  jav  a2  s  .c o  m*/

        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;// w  ww  .  j a  v a  2  s. c  o  m

    //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;

}