示例#1
0
        private static MimePart ConvertToMimePart(MailAttachmentData mailAttachmentData, string contentId = null)
        {
            var contentType = ContentType.Parse(
                !string.IsNullOrEmpty(mailAttachmentData.contentType)
                    ? mailAttachmentData.contentType
                    : MimeMapping.GetMimeMapping(mailAttachmentData.fileName));

            var mimePart = new MimePart(contentType)
            {
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName = mailAttachmentData.fileName
            };

            if (string.IsNullOrEmpty(contentId))
            {
                mimePart.ContentDisposition = new ContentDisposition(ContentDisposition.Attachment);
            }
            else
            {
                mimePart.ContentDisposition = new ContentDisposition(ContentDisposition.Inline);
                mimePart.ContentId          = contentId;
                mimePart.ContentType.Name   = mailAttachmentData.fileName;
            }

            MemoryStream ms;

            if (mailAttachmentData.data == null)
            {
                var s3Key = MailStoragePathCombiner.GerStoredFilePath(mailAttachmentData);

                ms = new MemoryStream();

                using (var stream = StorageManager
                                    .GetDataStoreForAttachments(mailAttachmentData.tenant)
                                    .GetReadStream(s3Key))
                {
                    stream.StreamCopyTo(ms);
                }
            }
            else
            {
                ms = new MemoryStream(mailAttachmentData.data);
            }

            mimePart.Content = new MimeContent(ms);

            Parameter param;

            if (mimePart.ContentDisposition != null && mimePart.ContentDisposition.Parameters.TryGetValue("filename", out param))
            {
                param.EncodingMethod = ParameterEncodingMethod.Rfc2047;
            }

            if (mimePart.ContentType.Parameters.TryGetValue("name", out param))
            {
                param.EncodingMethod = ParameterEncodingMethod.Rfc2047;
            }

            return(mimePart);
        }
示例#2
0
        public void StoreAttachmentCopy(int tenant, string user, MailAttachmentData attachment, string streamId)
        {
            try
            {
                if (attachment.streamId.Equals(streamId) && !attachment.isTemp)
                {
                    return;
                }

                string s3Key;

                var dataClient = MailDataStore.GetDataStore(tenant);

                if (attachment.needSaveToTemp || attachment.isTemp)
                {
                    s3Key = MailStoragePathCombiner.GetTempStoredFilePath(attachment);
                }
                else
                {
                    s3Key = MailStoragePathCombiner.GerStoredFilePath(attachment);
                }

                if (!dataClient.IsFile(s3Key))
                {
                    return;
                }

                attachment.fileNumber =
                    !string.IsNullOrEmpty(attachment.contentId) //Upload hack: embedded attachment have to be saved in 0 folder
                        ? 0
                        : attachment.fileNumber;

                var newS3Key = MailStoragePathCombiner.GetFileKey(user, streamId, attachment.fileNumber,
                                                                  attachment.storedName);

                var copyS3Url = dataClient.Copy(s3Key, string.Empty, newS3Key);

                attachment.storedFileUrl = MailStoragePathCombiner.GetStoredUrl(copyS3Url);

                attachment.streamId = streamId;

                attachment.tempStoredUrl = null;

                Log.DebugFormat("StoreAttachmentCopy() tenant='{0}', user_id='{1}', stream_id='{2}', new_s3_key='{3}', copy_s3_url='{4}', storedFileUrl='{5}',  filename='{6}'",
                                tenant, user, streamId, newS3Key, copyS3Url, attachment.storedFileUrl, attachment.fileName);
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("CopyAttachment(). filename='{0}', ctype='{1}' Exception:\r\n{2}\r\n",
                                attachment.fileName,
                                attachment.contentType,
                                ex.ToString());

                throw;
            }
        }
示例#3
0
        public static void ChangeAllImagesLinksToEmbedded(this MailDraftData draft, ILog log = null)
        {
            if (log == null)
            {
                log = new NullLog();
            }

            try
            {
                var doc = new HtmlDocument();
                doc.LoadHtml(draft.HtmlBody);
                var linkNodes = doc.DocumentNode.SelectNodes("//img[@src]");
                if (linkNodes == null)
                {
                    return;
                }

                foreach (var linkNode in linkNodes)
                {
                    var link = linkNode.Attributes["src"].Value;
                    log.InfoFormat("ChangeAllImagesLinksToEmbedded() Link to img link: {0}", link);

                    var fileName = Path.GetFileName(link);

                    var data = StorageManager.LoadLinkData(link, log);

                    if (!data.Any())
                    {
                        continue;
                    }

                    var attach = new MailAttachmentData
                    {
                        fileName   = fileName,
                        storedName = fileName,
                        contentId  = link.GetMd5(),
                        data       = data
                    };

                    log.InfoFormat("ChangeAllImagesLinksToEmbedded() Embedded img link contentId: {0}", attach.contentId);
                    linkNode.SetAttributeValue("src", "cid:" + attach.contentId);

                    if (draft.AttachmentsEmbedded.All(x => x.contentId != attach.contentId))
                    {
                        draft.AttachmentsEmbedded.Add(attach);
                    }
                }

                draft.HtmlBody = doc.DocumentNode.OuterHtml;
            }
            catch (Exception ex)
            {
                log.ErrorFormat("ChangeAllImagesLinksToEmbedded(): Exception: {0}", ex.ToString());
            }
        }
示例#4
0
        public static void ChangeSmileLinks(this MailDraftData draft, ILog log = null)
        {
            if (log == null)
            {
                log = new NullLog();
            }

            var baseSmileUrl = MailStoragePathCombiner.GetEditorSmileBaseUrl();

            var doc = new HtmlDocument();

            doc.LoadHtml(draft.HtmlBody);
            var linkNodes = doc.DocumentNode.SelectNodes("//img[@src and (contains(@src,'" + baseSmileUrl + "'))]");

            if (linkNodes == null)
            {
                return;
            }

            foreach (var linkNode in linkNodes)
            {
                var link = linkNode.Attributes["src"].Value;

                log.InfoFormat("ChangeSmileLinks() Link to smile: {0}", link);

                var fileName = Path.GetFileName(link);

                var data = StorageManager.LoadLinkData(link, log);

                if (!data.Any())
                {
                    continue;
                }

                var attach = new MailAttachmentData
                {
                    fileName   = fileName,
                    storedName = fileName,
                    contentId  = link.GetMd5(),
                    data       = data
                };

                log.InfoFormat("ChangeSmileLinks() Embedded smile contentId: {0}", attach.contentId);

                linkNode.SetAttributeValue("src", "cid:" + attach.contentId);

                if (draft.AttachmentsEmbedded.All(x => x.contentId != attach.contentId))
                {
                    draft.AttachmentsEmbedded.Add(attach);
                }
            }
            draft.HtmlBody = doc.DocumentNode.OuterHtml;
        }
        public object StoreAttachmentToDocuments(MailAttachmentData mailAttachmentData, string folderId)
        {
            if (mailAttachmentData == null)
            {
                return(-1);
            }

            var apiHelper = new ApiHelper(HttpContextScheme);

            using (var file = mailAttachmentData.ToAttachmentStream())
            {
                var uploadedFileId = apiHelper.UploadToDocuments(file.FileStream, file.FileName,
                                                                 mailAttachmentData.contentType, folderId, true);

                return(uploadedFileId);
            }
        }
示例#6
0
        public static AttachmentStream ToAttachmentStream(this MailAttachmentData mailAttachmentData, int offset = 0)
        {
            if (mailAttachmentData == null)
            {
                throw new InvalidOperationException("Attachment not found");
            }

            var storage        = MailDataStore.GetDataStore(mailAttachmentData.tenant);
            var attachmentPath = MailStoragePathCombiner.GerStoredFilePath(mailAttachmentData);
            var result         = new AttachmentStream
            {
                FileStream = storage.GetReadStream("", attachmentPath, offset),
                FileName   = mailAttachmentData.fileName,
                FileSize   = mailAttachmentData.size
            };

            return(result);
        }
        private static MailAttachmentData ConvertToMailAttachment(MimeEntity attachment, bool skipContentId = false)
        {
            var messagePart = attachment as MessagePart;
            var mimePart    = attachment as MimePart;

            if (messagePart == null && mimePart == null)
            {
                return(null);
            }

            var filename = attachment.ContentDisposition != null &&
                           !string.IsNullOrEmpty(attachment.ContentDisposition.FileName)
                ? attachment.ContentDisposition.FileName
                : attachment.ContentType != null && !string.IsNullOrEmpty(attachment.ContentType.Name)
                    ? attachment.ContentType.Name
                    : "";

            filename = MailUtil.ImproveFilename(filename, attachment.ContentType);

            var mailAttach = new MailAttachmentData
            {
                contentId       = skipContentId ? null : attachment.ContentId,
                fileName        = filename,
                contentType     = attachment.ContentType != null ? attachment.ContentType.MimeType : null,
                contentLocation =
                    !skipContentId && attachment.ContentLocation != null
                        ? attachment.ContentLocation.ToString()
                        : null,
                dataStream = new MemoryStream()
            };

            if (messagePart != null)
            {
                messagePart.Message.WriteTo(mailAttach.dataStream);
            }
            else
            {
                mimePart.Content.DecodeTo(mailAttach.dataStream);
            }

            mailAttach.size = mailAttach.dataStream.Length;

            return(mailAttach);
        }
        public static Attachment ToAttachmnet(this MailAttachmentData a, int mailId, bool isRemoved = false)
        {
            var attachment = new Attachment
            {
                Id         = a.fileId,
                MailId     = mailId,
                Name       = a.fileName,
                StoredName = a.storedName,
                Type       = a.contentType,
                Size       = a.size,
                FileNumber = a.fileNumber,
                IsRemoved  = isRemoved,
                ContentId  = a.contentId,
                Tenant     = a.tenant,
                MailboxId  = a.mailboxId
            };

            return(attachment);
        }
示例#9
0
        public static MailAttachmentData ToAttachmentData(Attachment attachment)
        {
            if (attachment == null)
            {
                return(null);
            }

            var a = new MailAttachmentData
            {
                fileId      = attachment.Id,
                fileName    = attachment.Name,
                storedName  = attachment.StoredName,
                contentType = attachment.Type,
                size        = attachment.Size,
                fileNumber  = attachment.FileNumber,
                streamId    = attachment.Stream,
                tenant      = attachment.Tenant,
                user        = attachment.User,
                contentId   = attachment.ContentId,
                mailboxId   = attachment.MailboxId
            };

            return(a);
        }
 public static string GetPreSignedUrl(MailAttachmentData mailAttachmentData)
 {
     return(GetPreSignedUri(mailAttachmentData.fileId, mailAttachmentData.tenant, mailAttachmentData.user, mailAttachmentData.streamId, mailAttachmentData.fileNumber, mailAttachmentData.storedName));
 }
 public static string GetTempStoredFilePath(MailAttachmentData mailAttachmentData)
 {
     return(GetTempFileKey(mailAttachmentData.user, mailAttachmentData.streamId, mailAttachmentData.fileNumber, mailAttachmentData.storedName));
 }
        private List <MailAttachmentData> FixHtmlBodyWithEmbeddedAttachments(MailComposeBase compose)
        {
            var embededAttachmentsForSaving = new List <MailAttachmentData>();

            var embeddedLinks = compose.GetEmbeddedAttachmentLinks();

            if (!embeddedLinks.Any())
            {
                return(embededAttachmentsForSaving);
            }

            var fckStorage              = StorageManager.GetDataStoreForCkImages(compose.Mailbox.TenantId);
            var attachmentStorage       = StorageManager.GetDataStoreForAttachments(compose.Mailbox.TenantId);
            var currentMailFckeditorUrl = fckStorage.GetUri(StorageManager.CKEDITOR_IMAGES_DOMAIN, "").ToString();
            var currentUserStorageUrl   = MailStoragePathCombiner.GetUserMailsDirectory(compose.Mailbox.UserId);

            var engine = new EngineFactory(compose.Mailbox.TenantId, compose.Mailbox.UserId);

            StorageManager storage = null;

            foreach (var embeddedLink in embeddedLinks)
            {
                try
                {
                    var isFckImage   = embeddedLink.StartsWith(currentMailFckeditorUrl);
                    var prefixLength = isFckImage
                        ? currentMailFckeditorUrl.Length
                        : embeddedLink.IndexOf(currentUserStorageUrl, StringComparison.Ordinal) +
                                       currentUserStorageUrl.Length + 1;
                    var fileLink = HttpUtility.UrlDecode(embeddedLink.Substring(prefixLength));
                    var fileName = Path.GetFileName(fileLink);
                    var attach   = new MailAttachmentData
                    {
                        fileName      = fileName,
                        storedName    = fileName,
                        contentId     = embeddedLink.GetMd5(),
                        storedFileUrl = fileLink,
                        streamId      = compose.StreamId,
                        user          = compose.Mailbox.UserId,
                        tenant        = compose.Mailbox.TenantId,
                        mailboxId     = compose.Mailbox.MailBoxId
                    };

                    var savedAttachment =
                        engine.AttachmentEngine.GetAttachment(
                            new ConcreteContentAttachmentExp(compose.Id, attach.contentId));

                    var savedAttachmentId = savedAttachment == null ? 0 : savedAttachment.fileId;

                    var attachmentWasSaved = savedAttachmentId != 0;
                    var currentImgStorage  = isFckImage ? fckStorage : attachmentStorage;
                    var domain             = isFckImage ? StorageManager.CKEDITOR_IMAGES_DOMAIN : compose.Mailbox.UserId;

                    if (compose.Id == 0 || !attachmentWasSaved)
                    {
                        attach.data = StorageManager.LoadDataStoreItemData(domain, fileLink, currentImgStorage);

                        if (storage == null)
                        {
                            storage = new StorageManager(compose.Mailbox.TenantId, compose.Mailbox.UserId);
                        }

                        storage.StoreAttachmentWithoutQuota(attach);

                        embededAttachmentsForSaving.Add(attach);
                    }

                    if (attachmentWasSaved)
                    {
                        attach = engine.AttachmentEngine.GetAttachment(
                            new ConcreteUserAttachmentExp(savedAttachmentId, compose.Mailbox.TenantId, compose.Mailbox.UserId));

                        var path = MailStoragePathCombiner.GerStoredFilePath(attach);
                        currentImgStorage    = attachmentStorage;
                        attach.storedFileUrl =
                            MailStoragePathCombiner.GetStoredUrl(currentImgStorage.GetUri(path));
                    }

                    compose.HtmlBody = compose.HtmlBody.Replace(embeddedLink, attach.storedFileUrl);
                }
                catch (Exception ex)
                {
                    Log.ErrorFormat("ChangeEmbededAttachmentLinksForStoring() failed with exception: {0}", ex.ToString());
                }
            }

            return(embededAttachmentsForSaving);
        }
示例#13
0
        public MailAttachmentData AttachFile(int tenant, string user, MailMessageData message,
                                             string name, Stream inputStream, long contentLength, string contentType = null, bool needSaveToTemp = false)
        {
            if (message == null)
            {
                throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "Message not found.");
            }

            if (string.IsNullOrEmpty(message.StreamId))
            {
                throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "StreamId is empty.");
            }

            var messageId = message.Id;

            var engine = new EngineFactory(tenant, user);

            var totalSize =
                engine.AttachmentEngine.GetAttachmentsSize(new ConcreteMessageAttachmentsExp(messageId, tenant, user));

            totalSize += contentLength;

            if (totalSize > Defines.ATTACHMENTS_TOTAL_SIZE_LIMIT)
            {
                throw new AttachmentsException(AttachmentsException.Types.TotalSizeExceeded,
                                               "Total size of all files exceeds limit!");
            }

            var fileNumber =
                engine.AttachmentEngine.GetAttachmentNextFileNumber(new ConcreteMessageAttachmentsExp(messageId, tenant,
                                                                                                      user));

            var attachment = new MailAttachmentData
            {
                fileName       = name,
                contentType    = string.IsNullOrEmpty(contentType) ? MimeMapping.GetMimeMapping(name) : contentType,
                needSaveToTemp = needSaveToTemp,
                fileNumber     = fileNumber,
                size           = contentLength,
                data           = inputStream.ReadToEnd(),
                streamId       = message.StreamId,
                tenant         = tenant,
                user           = user,
                mailboxId      = message.MailboxId
            };

            engine.QuotaEngine.QuotaUsedAdd(contentLength);

            try
            {
                var storage = new StorageManager(tenant, user);
                storage.StoreAttachmentWithoutQuota(attachment);
            }
            catch
            {
                engine.QuotaEngine.QuotaUsedDelete(contentLength);
                throw;
            }

            if (!needSaveToTemp)
            {
                int attachCount;

                using (var daoFactory = new DaoFactory())
                {
                    var db = daoFactory.DbManager;

                    using (var tx = db.BeginTransaction())
                    {
                        var daoAttachment = daoFactory.CreateAttachmentDao(tenant, user);

                        attachment.fileId = daoAttachment.SaveAttachment(attachment.ToAttachmnet(messageId));

                        attachCount = daoAttachment.GetAttachmentsCount(
                            new ConcreteMessageAttachmentsExp(messageId, tenant, user));

                        var daoMailInfo = daoFactory.CreateMailInfoDao(tenant, user);

                        daoMailInfo.SetFieldValue(
                            SimpleMessagesExp.CreateBuilder(tenant, user)
                            .SetMessageId(messageId)
                            .Build(),
                            MailTable.Columns.AttachCount,
                            attachCount);

                        engine.ChainEngine.UpdateMessageChainAttachmentsFlag(daoFactory, tenant, user, messageId);

                        tx.Commit();
                    }
                }

                if (attachCount == 1)
                {
                    var data = new MailWrapper
                    {
                        HasAttachments = true
                    };

                    engine.IndexEngine.Update(data, s => s.Where(m => m.Id, messageId), wrapper => wrapper.HasAttachments);
                }
            }

            return(attachment);
        }
示例#14
0
        public void StoreAttachmentWithoutQuota(MailAttachmentData mailAttachmentData)
        {
            try
            {
                if ((mailAttachmentData.dataStream == null || mailAttachmentData.dataStream.Length == 0) && (mailAttachmentData.data == null || mailAttachmentData.data.Length == 0))
                {
                    return;
                }

                if (string.IsNullOrEmpty(mailAttachmentData.fileName))
                {
                    mailAttachmentData.fileName = "attachment.ext";
                }

                var storage = MailDataStore.GetDataStore(Tenant);

                storage.QuotaController = null;

                if (string.IsNullOrEmpty(mailAttachmentData.storedName))
                {
                    mailAttachmentData.storedName = MailUtil.CreateStreamId();

                    var ext = Path.GetExtension(mailAttachmentData.fileName);

                    if (!string.IsNullOrEmpty(ext))
                    {
                        mailAttachmentData.storedName = Path.ChangeExtension(mailAttachmentData.storedName, ext);
                    }
                }

                mailAttachmentData.fileNumber =
                    !string.IsNullOrEmpty(mailAttachmentData.contentId) //Upload hack: embedded attachment have to be saved in 0 folder
                        ? 0
                        : mailAttachmentData.fileNumber;

                var attachmentPath = MailStoragePathCombiner.GerStoredFilePath(mailAttachmentData);

                if (mailAttachmentData.data != null)
                {
                    using (var reader = new MemoryStream(mailAttachmentData.data))
                    {
                        var uploadUrl = (mailAttachmentData.needSaveToTemp)
                            ? storage.Save("attachments_temp", attachmentPath, reader, mailAttachmentData.fileName)
                            : storage.Save(attachmentPath, reader, mailAttachmentData.fileName);

                        mailAttachmentData.storedFileUrl = MailStoragePathCombiner.GetStoredUrl(uploadUrl);
                    }
                }
                else
                {
                    var uploadUrl = (mailAttachmentData.needSaveToTemp)
                        ? storage.Save("attachments_temp", attachmentPath, mailAttachmentData.dataStream, mailAttachmentData.fileName)
                        : storage.Save(attachmentPath, mailAttachmentData.dataStream, mailAttachmentData.fileName);

                    mailAttachmentData.storedFileUrl = MailStoragePathCombiner.GetStoredUrl(uploadUrl);
                }

                if (mailAttachmentData.needSaveToTemp)
                {
                    mailAttachmentData.tempStoredUrl = mailAttachmentData.storedFileUrl;
                }
            }
            catch (Exception e)
            {
                Log.ErrorFormat("StoreAttachmentWithoutQuota(). filename: {0}, ctype: {1} Exception:\r\n{2}\r\n",
                                mailAttachmentData.fileName,
                                mailAttachmentData.contentType,
                                e.ToString());

                throw;
            }
        }
示例#15
0
        public override FileUploadResult ProcessUpload(HttpContext context)
        {
            var log = LogManager.GetLogger("ASC.Mail.FilesUploader");

            string message;

            var fileName = string.Empty;

            MailAttachmentData mailAttachmentData = null;

            try
            {
                if (!FileToUpload.HasFilesToUpload(context))
                {
                    throw new Exception(MailScriptResource.AttachmentsBadInputParamsError);
                }

                if (!SecurityContext.IsAuthenticated)
                {
                    throw new HttpException(403, "Access denied.");
                }

                Thread.CurrentThread.CurrentCulture   = CurrentCulture;
                Thread.CurrentThread.CurrentUICulture = CurrentCulture;

                var mailId         = Convert.ToInt32(context.Request["messageId"]);
                var copyToMy       = Convert.ToInt32(context.Request["copyToMy"]);
                var needSaveToTemp = Convert.ToBoolean(context.Request["needSaveToTemp"]);

                if (mailId < 1)
                {
                    throw new AttachmentsException(AttachmentsException.Types.MessageNotFound,
                                                   "Message not yet saved!");
                }

                var engine = new EngineFactory(TenantId, Username);

                var item = engine.MessageEngine.GetMessage(mailId, new MailMessageData.Options());
                if (item == null)
                {
                    throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "Message not found.");
                }

                if (string.IsNullOrEmpty(item.StreamId))
                {
                    throw new AttachmentsException(AttachmentsException.Types.BadParams, "Have no stream");
                }

                var postedFile = new FileToUpload(context);

                fileName = context.Request["name"];

                if (string.IsNullOrEmpty(fileName))
                {
                    throw new AttachmentsException(AttachmentsException.Types.BadParams, "Empty name param");
                }

                if (copyToMy == 1)
                {
                    var uploadedFile = FileUploader.Exec(Global.FolderMy.ToString(), fileName,
                                                         postedFile.ContentLength, postedFile.InputStream, true);

                    return(new FileUploadResult
                    {
                        Success = true,
                        FileName = uploadedFile.Title,
                        FileURL = FileShareLink.GetLink(uploadedFile, false),
                        Data = new MailAttachmentData
                        {
                            fileId = Convert.ToInt32(uploadedFile.ID),
                            fileName = uploadedFile.Title,
                            size = uploadedFile.ContentLength,
                            contentType = uploadedFile.ConvertedType,
                            attachedAsLink = true,
                            tenant = TenantId,
                            user = Username
                        }
                    });
                }

                mailAttachmentData = engine.AttachmentEngine
                                     .AttachFileToDraft(TenantId, Username, mailId, fileName, postedFile.InputStream,
                                                        postedFile.ContentLength, null, postedFile.NeedSaveToTemp);

                return(new FileUploadResult
                {
                    Success = true,
                    FileName = mailAttachmentData.fileName,
                    FileURL = mailAttachmentData.storedFileUrl,
                    Data = mailAttachmentData
                });
            }
            catch (HttpException he)
            {
                log.Error("FileUpload handler failed", he);

                context.Response.StatusCode = he.GetHttpCode();
                message = he.Message != null
                    ? HttpUtility.HtmlEncode(he.Message)
                    : MailApiErrorsResource.ErrorInternalServer;
            }
            catch (AttachmentsException ex)
            {
                log.Error("FileUpload handler failed", ex);

                switch (ex.ErrorType)
                {
                case AttachmentsException.Types.BadParams:
                    message = MailScriptResource.AttachmentsBadInputParamsError;
                    break;

                case AttachmentsException.Types.EmptyFile:
                    message = MailScriptResource.AttachmentsEmptyFileNotSupportedError;
                    break;

                case AttachmentsException.Types.MessageNotFound:
                    message = MailScriptResource.AttachmentsMessageNotFoundError;
                    break;

                case AttachmentsException.Types.TotalSizeExceeded:
                    message = MailScriptResource.AttachmentsTotalLimitError;
                    break;

                case AttachmentsException.Types.DocumentNotFound:
                    message = MailScriptResource.AttachmentsDocumentNotFoundError;
                    break;

                case AttachmentsException.Types.DocumentAccessDenied:
                    message = MailScriptResource.AttachmentsDocumentAccessDeniedError;
                    break;

                default:
                    message = MailScriptResource.AttachmentsUnknownError;
                    break;
                }
            }
            catch (TenantQuotaException ex)
            {
                log.Error("FileUpload handler failed", ex);
                message = ex.Message;
            }
            catch (Exception ex)
            {
                log.Error("FileUpload handler failed", ex);
                message = MailScriptResource.AttachmentsUnknownError;
            }

            return(new FileUploadResult
            {
                Success = false,
                FileName = fileName,
                Data = mailAttachmentData,
                Message = string.IsNullOrEmpty(message) ? MailApiErrorsResource.ErrorInternalServer : message
            });
        }
        public static MailMessageData CreateCorruptedMesage(this MimeMessage message,
                                                            FolderType folder = FolderType.Inbox,
                                                            bool unread       = false,
                                                            string chainId    = "",
                                                            string streamId   = "")
        {
            var mailMessage = new MailMessageData
            {
                HasParseError = true
            };

            MailUtil.SkipErrors(() => mailMessage.Date = MailUtil.IsDateCorrect(message.Date.UtcDateTime)
                ? message.Date.UtcDateTime
                : DateTime.UtcNow);

            MailUtil.SkipErrors(() => mailMessage.MimeMessageId = (string.IsNullOrEmpty(message.MessageId) ? MailUtil.CreateMessageId() : message.MessageId)
                                                                  .Trim('<', '>'));

            MailUtil.SkipErrors(() => mailMessage.ChainId = string.IsNullOrEmpty(chainId) ? mailMessage.MimeMessageId : chainId);

            MailUtil.SkipErrors(() => mailMessage.MimeReplyToId = mailMessage.ChainId.Equals(mailMessage.MimeMessageId) ? null : message.InReplyTo.Trim('<', '>'));

            MailUtil.SkipErrors(() => mailMessage.ReplyTo = message.ReplyTo.ToString());

            MailUtil.SkipErrors(() => mailMessage.From = message.From.ToString());

            MailUtil.SkipErrors(() =>
                                mailMessage.FromEmail =
                                    message.From != null && message.From.Mailboxes != null && message.From.Mailboxes.Any()
                        ? message.From.Mailboxes.First().Address
                        : "");

            MailUtil.SkipErrors(() => mailMessage.ToList = message.To.Mailboxes.Select(s => MailUtil.ExecuteSafe(() => new MailAddress(s.Address, s.Name))).ToList());

            MailUtil.SkipErrors(() => mailMessage.To = string.Join(", ", message.To.Mailboxes.Select(s => s.ToString())));

            MailUtil.SkipErrors(() => mailMessage.CcList = message.Cc.Mailboxes.Select(s => MailUtil.ExecuteSafe(() => new MailAddress(s.Address, s.Name))).ToList());

            MailUtil.SkipErrors(() => mailMessage.Cc = string.Join(", ", message.Cc.Mailboxes.Select(s => s.ToString())));

            MailUtil.SkipErrors(() => mailMessage.Bcc = string.Join(", ", message.Bcc.Mailboxes.Select(s => s.ToString())));

            MailUtil.SkipErrors(() => mailMessage.Subject = message.Subject ?? string.Empty);

            MailUtil.SkipErrors(() => mailMessage.Important = message.Importance == MessageImportance.High || message.Priority == MessagePriority.Urgent);

            mailMessage.HtmlBodyStream = new MemoryStream();

            using (var sw = new StreamWriter(mailMessage.HtmlBodyStream, Encoding.UTF8, 1024, true))
            {
                sw.Write("<body><pre>&nbsp;</pre></body>");
                sw.Flush();
            }

            mailMessage.Size = mailMessage.HtmlBodyStream.Length;

            mailMessage.HeaderFieldNames = new NameValueCollection();

            message.Headers
            .ToList()
            .ForEach(h => MailUtil.SkipErrors(() => mailMessage.HeaderFieldNames.Add(h.Field, h.Value)));

            mailMessage.Folder       = folder;
            mailMessage.IsNew        = unread;
            mailMessage.StreamId     = string.IsNullOrEmpty(streamId) ? MailUtil.CreateStreamId() : streamId;
            mailMessage.TextBodyOnly = true;
            mailMessage.Introduction = "";
            mailMessage.Attachments  = new List <MailAttachmentData>();

            MailUtil.SkipErrors(() =>
            {
                var mailAttach = new MailAttachmentData
                {
                    contentId       = null,
                    fileName        = "message.eml",
                    contentType     = "message/rfc822",
                    contentLocation = null,
                    dataStream      = new MemoryStream()
                };

                message.WriteTo(mailAttach.dataStream);

                mailAttach.size = mailAttach.dataStream.Length;

                mailMessage.Attachments.Add(mailAttach);
            });

            return(mailMessage);
        }