public Message addMessage(
      long userId,
      long folderId,
      String sender,
      String to,
      String cc,
      String bcc,
      Date sentDate,
      String subject,
      String body,
      String flags,
      long remoteMessageId)
      throws PortalException, SystemException {

    // Message

    User user = userPersistence.findByPrimaryKey(userId);
    Folder folder = folderPersistence.findByPrimaryKey(folderId);
    Date now = new Date();

    long messageId = counterLocalService.increment();

    Message message = messagePersistence.create(messageId);

    message.setCompanyId(user.getCompanyId());
    message.setUserId(user.getUserId());
    message.setUserName(user.getFullName());
    message.setCreateDate(now);
    message.setModifiedDate(now);
    message.setAccountId(folder.getAccountId());
    message.setFolderId(folderId);
    message.setSender(sender);
    message.setTo(to);
    message.setCc(cc);
    message.setBcc(bcc);
    message.setSentDate(sentDate);
    message.setSubject(subject);
    message.setPreview(getPreview(body));
    message.setBody(getBody(body));
    message.setFlags(flags);
    message.setSize(getSize(messageId, body));
    message.setRemoteMessageId(remoteMessageId);

    messagePersistence.update(message, false);

    // Indexer

    Indexer indexer = IndexerRegistryUtil.getIndexer(Message.class);

    indexer.reindex(message);

    return message;
  }
  public Message updateMessage(
      long messageId,
      long folderId,
      String sender,
      String to,
      String cc,
      String bcc,
      Date sentDate,
      String subject,
      String body,
      String flags,
      long remoteMessageId)
      throws PortalException, SystemException {

    // Message

    Message message = messagePersistence.findByPrimaryKey(messageId);

    message.setModifiedDate(new Date());
    message.setFolderId(folderId);
    message.setSender(sender);
    message.setTo(to);
    message.setCc(cc);
    message.setBcc(bcc);
    message.setSentDate(sentDate);
    message.setSubject(subject);
    message.setPreview(getPreview(body));
    message.setBody(getBody(body));
    message.setFlags(flags);
    message.setSize(getSize(messageId, body));
    message.setRemoteMessageId(remoteMessageId);

    messagePersistence.update(message, false);

    // Indexer

    Indexer indexer = IndexerRegistryUtil.getIndexer(Message.class);

    indexer.reindex(message);

    return message;
  }