Ejemplo n.º 1
0
        public MailMessage Save(MailComposeBase compose)
        {
            var embededAttachmentsForSaving = FixHtmlBodyWithEmbeddedAttachments(compose);

            var message = compose.ToMailMessage();

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

            var addIndex = compose.Id == 0;

            var attachmentsToRestore = message.Attachments.Where(att => att.streamId != message.StreamId || att.isTemp).ToList();

            var needRestoreAttachments = attachmentsToRestore.Any();

            if (needRestoreAttachments)
            {
                message.Attachments.ForEach(
                    attachment =>
                    engine.AttachmentEngine.StoreAttachmentCopy(compose.Mailbox.TenantId, compose.Mailbox.UserId,
                                                                attachment, compose.StreamId));
            }

            MessageEngine.StoreMailBody(compose.Mailbox, message, Log);

            long usedQuota;

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

                using (var tx = db.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    compose.Id = engine.MessageEngine.MailSave(daoFactory, compose.Mailbox, message, compose.Id, message.Folder, message.Folder, null,
                                                               string.Empty, string.Empty, false, out usedQuota);

                    message.Id = compose.Id;

                    if (compose.AccountChanged)
                    {
                        engine.ChainEngine.UpdateChain(daoFactory, message.ChainId, message.Folder, null, compose.PreviousMailboxId,
                                                       compose.Mailbox.TenantId, compose.Mailbox.UserId);
                    }

                    var daoMailInfo = daoFactory.CreateMailInfoDao(compose.Mailbox.TenantId, compose.Mailbox.UserId);

                    if (compose.Id > 0 && needRestoreAttachments)
                    {
                        var daoAttachment       = daoFactory.CreateAttachmentDao(compose.Mailbox.TenantId, compose.Mailbox.UserId);
                        var existingAttachments = daoAttachment.GetAttachments(
                            new ConcreteMessageAttachmentsExp(compose.Id, compose.Mailbox.TenantId, compose.Mailbox.UserId));

                        foreach (var attachment in message.Attachments)
                        {
                            if (existingAttachments.Any(x => x.Id == attachment.fileId))
                            {
                                continue;
                            }

                            var attach = attachment.ToAttachmnet(compose.Id);
                            attach.Id = 0;

                            var newId = daoAttachment.SaveAttachment(attach);
                            attachment.fileId = newId;
                        }

                        if (message.Attachments.Any())
                        {
                            var count = daoAttachment.GetAttachmentsCount(
                                new ConcreteMessageAttachmentsExp(compose.Id, compose.Mailbox.TenantId, compose.Mailbox.UserId));

                            daoMailInfo.SetFieldValue(
                                SimpleMessagesExp.CreateBuilder(compose.Mailbox.TenantId, compose.Mailbox.UserId)
                                .SetMessageId(compose.Id)
                                .Build(),
                                MailTable.Columns.AttachCount,
                                count);
                        }
                    }

                    if (compose.Id > 0 && embededAttachmentsForSaving.Any())
                    {
                        var daoAttachment = daoFactory.CreateAttachmentDao(compose.Mailbox.TenantId, compose.Mailbox.UserId);

                        foreach (var attachment in embededAttachmentsForSaving)
                        {
                            var newId = daoAttachment.SaveAttachment(attachment.ToAttachmnet(compose.Id));
                            attachment.fileId = newId;
                        }

                        if (message.Attachments.Any())
                        {
                            var count = daoAttachment.GetAttachmentsCount(
                                new ConcreteMessageAttachmentsExp(compose.Id, compose.Mailbox.TenantId, compose.Mailbox.UserId));

                            daoMailInfo.SetFieldValue(
                                SimpleMessagesExp.CreateBuilder(compose.Mailbox.TenantId, compose.Mailbox.UserId)
                                .SetMessageId(compose.Id)
                                .Build(),
                                MailTable.Columns.AttachCount,
                                count);
                        }
                    }

                    engine.ChainEngine.UpdateChain(daoFactory, message.ChainId, message.Folder, null, compose.Mailbox.MailBoxId, compose.Mailbox.TenantId,
                                                   compose.Mailbox.UserId);

                    if (compose.AccountChanged)
                    {
                        var daoCrmLink = daoFactory.CreateCrmLinkDao(compose.Mailbox.TenantId, compose.Mailbox.UserId);

                        daoCrmLink.UpdateCrmLinkedMailboxId(message.ChainId, compose.PreviousMailboxId,
                                                            compose.Mailbox.MailBoxId);
                    }

                    tx.Commit();
                }
            }

            if (usedQuota > 0)
            {
                engine.QuotaEngine.QuotaUsedDelete(usedQuota);
            }

            if (addIndex)
            {
                engine.IndexEngine.Add(message.ToMailWrapper(compose.Mailbox.TenantId, new Guid(compose.Mailbox.UserId)));
            }
            else
            {
                engine.IndexEngine.Update(new List <MailWrapper>
                {
                    message.ToMailWrapper(compose.Mailbox.TenantId,
                                          new Guid(compose.Mailbox.UserId))
                });
            }

            try
            {
                var tempStorage = MailDataStore.GetDataStore(compose.Mailbox.TenantId);

                tempStorage.DeleteDirectory("attachments_temp", compose.Mailbox.UserId + "/" + compose.StreamId + "/");
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("Clearing temp storage failed with exception: {0}", ex.ToString());
            }

            return(message);
        }
Ejemplo n.º 2
0
        private void AddNotificationAlertToMailbox(MailDraftData draft, Exception exOnSanding)
        {
            try
            {
                var sbMessage = new StringBuilder(1024);

                sbMessage
                .AppendFormat("<div style=\"max-width:500px;font: normal 12px Arial, Tahoma,sans-serif;\"><p style=\"color:gray;font: normal 12px Arial, Tahoma,sans-serif;\">{0}</p>",
                              DaemonLabels.AutomaticMessageLabel)
                .AppendFormat("<p style=\"font: normal 12px Arial, Tahoma,sans-serif;\">{0}</p>", DaemonLabels.MessageIdentificator
                              .Replace("{subject}", draft.Subject)
                              .Replace("{date}", DateTime.Now.ToString(CultureInfo.InvariantCulture)))
                .AppendFormat("<div><p style=\"font: normal 12px Arial, Tahoma,sans-serif;\">{0}:</p><ul style=\"color:#333;font: normal 12px Arial, Tahoma,sans-serif;\">",
                              DaemonLabels.RecipientsLabel);

                draft.To.ForEach(rcpt => sbMessage.AppendFormat("<li>{0}</li>", HttpUtility.HtmlEncode(rcpt)));
                draft.Cc.ForEach(rcpt => sbMessage.AppendFormat("<li>{0}</li>", HttpUtility.HtmlEncode(rcpt)));
                draft.Bcc.ForEach(rcpt => sbMessage.AppendFormat("<li>{0}</li>", HttpUtility.HtmlEncode(rcpt)));

                sbMessage
                .AppendFormat("</ul>")
                .AppendFormat("<p style=\"font: normal 12px Arial, Tahoma,sans-serif;\">{0}</p>",
                              DaemonLabels.RecommendationsLabel
                              .Replace("{account_name}", "<b>" + draft.From + "</b>"))
                .AppendFormat(
                    "<a id=\"delivery_failure_button\" mailid={0} class=\"button blue\" style=\"margin-right:8px;\">{1}</a></div>",
                    draft.Id, DaemonLabels.TryAgainButtonLabel)
                .AppendFormat("<p style=\"font: normal 12px Arial, Tahoma,sans-serif;\">{0}</p>",
                              DaemonLabels.FaqInformationLabel
                              .Replace("{url_begin}",
                                       "<a id=\"delivery_failure_faq_link\" target=\"blank\" href=\"#\" class=\"link underline\">")
                              .Replace("{url_end}", "</a>"));

                const int max_length = 300;

                var smtpResponse = string.IsNullOrEmpty(exOnSanding.Message)
                    ? "no response"
                    : exOnSanding.Message.Length > max_length
                        ? exOnSanding.Message.Substring(0, max_length)
                        : exOnSanding.Message;

                sbMessage.AppendFormat("<p style=\"color:gray;font: normal 12px Arial, Tahoma,sans-serif;\">{0}: \"{1}\"</p></div>", DaemonLabels.ReasonLabel,
                                       smtpResponse);

                draft.Mailbox.Name = "";

                var messageDelivery = new MailDraftData(0, draft.Mailbox, DaemonLabels.DaemonEmail,
                                                        new List <string>()
                {
                    draft.From
                }, new List <string>(), new List <string>(),
                                                        DaemonLabels.SubjectLabel,
                                                        MailUtil.CreateStreamId(), "", true, new List <int>(), sbMessage.ToString(), MailUtil.CreateStreamId(),
                                                        new List <MailAttachmentData>());

                // SaveToDraft To Inbox
                var notifyMessageItem = messageDelivery.ToMailMessage();
                notifyMessageItem.ChainId = notifyMessageItem.MimeMessageId;
                notifyMessageItem.IsNew   = true;

                MessageEngine.StoreMailBody(draft.Mailbox, notifyMessageItem, Log);

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

                var mailDaemonMessageid = engine.MessageEngine.MailSave(draft.Mailbox, notifyMessageItem, 0,
                                                                        FolderType.Inbox, FolderType.Inbox, null,
                                                                        string.Empty, string.Empty, false);

                engine.AlertEngine.CreateDeliveryFailureAlert(
                    draft.Mailbox.TenantId,
                    draft.Mailbox.UserId,
                    draft.Mailbox.MailBoxId,
                    draft.Subject,
                    draft.From,
                    draft.Id,
                    mailDaemonMessageid);
            }
            catch (Exception exError)
            {
                Log.ErrorFormat("AddNotificationAlertToMailbox() in MailboxId={0} failed with exception:\r\n{1}",
                                draft.Mailbox.MailBoxId, exError.ToString());
            }
        }
Ejemplo n.º 3
0
        public int CreateReplyToSampleMessage(int id, string body, bool add2Index = false)
        {
            var message = _engineFactory.MessageEngine.GetMessage(id, new MailMessage.Options());

            if (message == null)
            {
                throw new ArgumentException("Message with id not found");
            }

            var mbox = _engineFactory.MailboxEngine.GetMailboxData(
                new СoncreteUserMailboxExp(message.MailboxId, TenantId, Username));

            if (mbox == null)
            {
                throw new ArgumentException("Mailbox not found");
            }

            var mimeMessageId = MailUtil.CreateMessageId();

            var sampleMessage = new MailMessage
            {
                Date            = DateTime.UtcNow,
                MimeMessageId   = mimeMessageId,
                MimeReplyToId   = message.MimeMessageId,
                ChainId         = message.MimeMessageId,
                ReplyTo         = message.FromEmail,
                To              = message.FromEmail,
                Cc              = "",
                Bcc             = "",
                Subject         = "Re: " + message.Subject,
                Important       = message.Important,
                TextBodyOnly    = false,
                Attachments     = new List <MailAttachmentData>(),
                Size            = body.Length,
                MailboxId       = mbox.MailBoxId,
                HtmlBody        = body,
                Introduction    = body,
                Folder          = FolderType.Sent,
                RestoreFolderId = FolderType.Sent,
                IsNew           = false,
                StreamId        = MailUtil.CreateStreamId(),
                From            = MailUtil.CreateFullEmail(mbox.Name, mbox.EMail.Address),
                FromEmail       = mbox.EMail.Address
            };

            MessageEngine.StoreMailBody(mbox, sampleMessage, Log);

            var replyId = _engineFactory.MessageEngine.MailSave(mbox, sampleMessage, 0, FolderType.Sent, FolderType.Sent, null,
                                                                SAMPLE_REPLY_UIDL, "", false);

            if (!add2Index)
            {
                return(replyId);
            }

            var replyMessage = _engineFactory.MessageEngine.GetMessage(replyId, new MailMessageData.Options());

            var wrapper = replyMessage.ToMailWrapper(mbox.TenantId, new Guid(mbox.UserId));

            _engineFactory.IndexEngine.Add(wrapper);

            return(replyId);
        }
Ejemplo n.º 4
0
        public int CreateSampleMessage(
            int?folderId,
            int?mailboxId,
            List <string> to,
            List <string> cc,
            List <string> bcc,
            bool importance,
            bool unread,
            string subject,
            string body,
            string calendarUid   = null,
            DateTime?date        = null,
            List <int> tagIds    = null,
            string fromAddress   = null,
            bool add2Index       = false,
            string mimeMessageId = null,
            uint?userFolderId    = null)
        {
            var folder = folderId.HasValue ? (FolderType)folderId.Value : FolderType.Inbox;

            if (!MailFolder.IsIdOk(folder))
            {
                throw new ArgumentException(@"Invalid folder id", "folderId");
            }

            if (!mailboxId.HasValue)
            {
                throw new ArgumentException(@"Invalid mailbox id", "mailboxId");
            }

            var accounts = _engineFactory.AccountEngine.GetAccountInfoList().ToAccountData().ToList();

            var account = mailboxId.HasValue
                ? accounts.FirstOrDefault(a => a.MailboxId == mailboxId)
                : accounts.FirstOrDefault(a => a.IsDefault) ?? accounts.FirstOrDefault();

            if (account == null)
            {
                throw new ArgumentException("Mailbox not found");
            }

            var mbox = _engineFactory.MailboxEngine.GetMailboxData(
                new СoncreteUserMailboxExp(account.MailboxId, TenantId, Username));

            if (mbox == null)
            {
                throw new ArgumentException("no such mailbox");
            }

            var internalId = string.IsNullOrEmpty(mimeMessageId) ? MailUtil.CreateMessageId() : mimeMessageId;

            var restoreFolder = folder == FolderType.Spam || folder == FolderType.Trash
                ? FolderType.Inbox
                : folder;

            string sampleBody;
            string sampleIntro;

            if (!to.Any())
            {
                to = new List <string> {
                    mbox.EMail.Address
                };
            }

            if (!string.IsNullOrEmpty(body))
            {
                sampleBody  = body;
                sampleIntro = MailUtil.GetIntroduction(body);
            }
            else
            {
                sampleBody  = LOREM_IPSUM_BODY;
                sampleIntro = LOREM_IPSUM_INTRO;
            }

            var sampleMessage = new MailMessage
            {
                Date            = date ?? DateTime.UtcNow,
                MimeMessageId   = internalId,
                MimeReplyToId   = null,
                ChainId         = internalId,
                ReplyTo         = "",
                To              = string.Join(", ", to.ToArray()),
                Cc              = cc.Any() ? string.Join(", ", cc.ToArray()) : "",
                Bcc             = bcc.Any() ? string.Join(", ", bcc.ToArray()) : "",
                Subject         = string.IsNullOrEmpty(subject) ? LOREM_IPSUM_SUBJECT : subject,
                Important       = importance,
                TextBodyOnly    = false,
                Attachments     = new List <MailAttachmentData>(),
                Size            = sampleBody.Length,
                MailboxId       = mbox.MailBoxId,
                HtmlBody        = sampleBody,
                Introduction    = sampleIntro,
                Folder          = folder,
                RestoreFolderId = restoreFolder,
                IsNew           = unread,
                StreamId        = MailUtil.CreateStreamId(),
                CalendarUid     = calendarUid
            };

            if (!string.IsNullOrEmpty(fromAddress))
            {
                var from = Parser.ParseAddress(fromAddress);

                sampleMessage.From      = from.ToString();
                sampleMessage.FromEmail = from.Email;
            }
            else
            {
                sampleMessage.From      = MailUtil.CreateFullEmail(mbox.Name, mbox.EMail.Address);
                sampleMessage.FromEmail = mbox.EMail.Address;
            }

            if (tagIds != null && tagIds.Any())
            {
                sampleMessage.TagIds = tagIds;
            }

            MessageEngine.StoreMailBody(mbox, sampleMessage, Log);

            var id = _engineFactory.MessageEngine.MailSave(mbox, sampleMessage, 0, folder, restoreFolder, userFolderId,
                                                           SAMPLE_UIDL, "", false);

            if (!add2Index)
            {
                return(id);
            }

            var message = _engineFactory.MessageEngine.GetMessage(id, new MailMessageData.Options());

            message.IsNew = unread;

            var wrapper = message.ToMailWrapper(mbox.TenantId, new Guid(mbox.UserId));

            _engineFactory.IndexEngine.Add(wrapper);

            return(id);
        }
Ejemplo n.º 5
0
        public MailMessage Save(MailComposeBase draft)
        {
            var embededAttachmentsForSaving = FixHtmlBodyWithEmbeddedAttachments(draft);

            var message = draft.ToMailMessage();

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

            var addIndex = draft.Id == 0;

            var needRestoreAttachments = draft.Id == 0 && message.Attachments.Any();

            if (needRestoreAttachments)
            {
                message.Attachments.ForEach(
                    attachment =>
                    engine.AttachmentEngine.StoreAttachmentCopy(draft.Mailbox.TenantId, draft.Mailbox.UserId,
                                                                attachment, draft.StreamId));
            }

            MessageEngine.StoreMailBody(draft.Mailbox, message, Log);

            long usedQuota;

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

                using (var tx = db.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    draft.Id = engine.MessageEngine.MailSave(daoFactory, draft.Mailbox, message, draft.Id, message.Folder, message.Folder, null,
                                                             string.Empty, string.Empty, false, out usedQuota);

                    message.Id = draft.Id;

                    if (draft.AccountChanged)
                    {
                        engine.ChainEngine.UpdateChain(daoFactory, message.ChainId, message.Folder, null, draft.PreviousMailboxId,
                                                       draft.Mailbox.TenantId, draft.Mailbox.UserId);
                    }

                    var daoMailInfo = daoFactory.CreateMailInfoDao(draft.Mailbox.TenantId, draft.Mailbox.UserId);

                    if (draft.Id > 0 && needRestoreAttachments)
                    {
                        var daoAttachment = daoFactory.CreateAttachmentDao(draft.Mailbox.TenantId, draft.Mailbox.UserId);

                        foreach (var attachment in message.Attachments)
                        {
                            var attach = attachment.ToAttachmnet(draft.Id);
                            attach.Id = 0;

                            var newId = daoAttachment.SaveAttachment(attach);
                            attachment.fileId = newId;
                        }

                        if (message.Attachments.Any())
                        {
                            var count = daoAttachment.GetAttachmentsCount(
                                new ConcreteMessageAttachmentsExp(draft.Id, draft.Mailbox.TenantId, draft.Mailbox.UserId));

                            daoMailInfo.SetFieldValue(
                                SimpleMessagesExp.CreateBuilder(draft.Mailbox.TenantId, draft.Mailbox.UserId)
                                .SetMessageId(draft.Id)
                                .Build(),
                                MailTable.Columns.AttachCount,
                                count);
                        }
                    }

                    if (draft.Id > 0 && embededAttachmentsForSaving.Any())
                    {
                        var daoAttachment = daoFactory.CreateAttachmentDao(draft.Mailbox.TenantId, draft.Mailbox.UserId);

                        foreach (var attachment in embededAttachmentsForSaving)
                        {
                            var newId = daoAttachment.SaveAttachment(attachment.ToAttachmnet(draft.Id));
                            attachment.fileId = newId;
                        }

                        if (message.Attachments.Any())
                        {
                            var count = daoAttachment.GetAttachmentsCount(
                                new ConcreteMessageAttachmentsExp(draft.Id, draft.Mailbox.TenantId, draft.Mailbox.UserId));

                            daoMailInfo.SetFieldValue(
                                SimpleMessagesExp.CreateBuilder(draft.Mailbox.TenantId, draft.Mailbox.UserId)
                                .SetMessageId(draft.Id)
                                .Build(),
                                MailTable.Columns.AttachCount,
                                count);
                        }
                    }

                    engine.ChainEngine.UpdateChain(daoFactory, message.ChainId, message.Folder, null, draft.Mailbox.MailBoxId, draft.Mailbox.TenantId,
                                                   draft.Mailbox.UserId);

                    if (draft.AccountChanged)
                    {
                        var daoCrmLink = daoFactory.CreateCrmLinkDao(draft.Mailbox.TenantId, draft.Mailbox.UserId);

                        daoCrmLink.UpdateCrmLinkedMailboxId(message.ChainId, draft.PreviousMailboxId,
                                                            draft.Mailbox.MailBoxId);
                    }

                    tx.Commit();
                }
            }

            if (usedQuota > 0)
            {
                engine.QuotaEngine.QuotaUsedDelete(usedQuota);
            }

            if (addIndex)
            {
                engine.IndexEngine.Add(message.ToMailWrapper(draft.Mailbox.TenantId, new Guid(draft.Mailbox.UserId)));
            }
            else
            {
                engine.IndexEngine.Update(new List <MailWrapper>
                {
                    message.ToMailWrapper(draft.Mailbox.TenantId,
                                          new Guid(draft.Mailbox.UserId))
                });
            }

            return(message);
        }