private void btnForgotPwd_Click(object sender, RoutedEventArgs e)
        {
            ESchoolDiary.Student student = ESchoolDiary.DataEngine.GetStudent(txtBoxID.Text);

            if (student != null)
            {
                string newPassword = GeneratePassword();
                string subject = "New password for ESchoolDiary";
                string from = "*****@*****.**";
                string body = String.Format("Your new password for ESchoolDiary is: {0}", newPassword);

                MailUtil mailUtil = new MailUtil();

                mailUtil.SendMail(student.EMail, subject, from, body);
                student.Password = newPassword;

                MessageBox.Show("Your new password has been sent to your e-mail.");

                this.Close();

                // Send mail to the parent.
                mailUtil.SendMail(student.ParrentEmail, subject, from, body);
            }
            else
            {
                MessageBox.Show("Invalid username.");
            }
        }
Example #2
0
        public long Send(int id,
                         string from,
                         List <string> to,
                         List <string> cc,
                         List <string> bcc,
                         string mimeReplyToId,
                         bool importance,
                         string subject,
                         List <int> tags,
                         string body,
                         List <MailAttachmentData> attachments,
                         Files.Core.Security.FileShare fileLinksShareMode,
                         string calendarIcs,
                         bool isAutoreply,
                         bool requestReceipt,
                         bool requestRead,
                         DeliveryFailureMessageTranslates translates = null)
        {
            if (id < 1)
            {
                id = 0;
            }

            if (string.IsNullOrEmpty(from))
            {
                throw new ArgumentNullException("from");
            }

            if (!to.Any())
            {
                throw new ArgumentNullException("to");
            }

            var mailAddress = new MailAddress(from);

            var engine = new EngineFactory(Tenant, User);

            var accounts = engine.AccountEngine.GetAccountInfoList().ToAccountData();

            var account = accounts.FirstOrDefault(a => a.Email.ToLower().Equals(mailAddress.Address));

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

            if (account.IsGroup)
            {
                throw new InvalidOperationException("Sending emails from a group address is forbidden");
            }

            var mbox = engine.MailboxEngine.GetMailboxData(
                new СoncreteUserMailboxExp(account.MailboxId, Tenant, User));

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

            if (!mbox.Enabled)
            {
                throw new InvalidOperationException("Sending emails from a disabled account is forbidden");
            }

            string mimeMessageId, streamId;

            var previousMailboxId = mbox.MailBoxId;

            if (id > 0)
            {
                var message = engine.MessageEngine.GetMessage(id, new MailMessage.Options
                {
                    LoadImages    = false,
                    LoadBody      = true,
                    NeedProxyHttp = Defines.NeedProxyHttp,
                    NeedSanitizer = false
                });

                if (message.Folder != FolderType.Draft)
                {
                    throw new InvalidOperationException("Sending emails is permitted only in the Drafts folder");
                }

                mimeMessageId = message.MimeMessageId;

                streamId = message.StreamId;

                foreach (var attachment in attachments)
                {
                    attachment.streamId = streamId;
                }

                previousMailboxId = message.MailboxId;
            }
            else
            {
                mimeMessageId = MailUtil.CreateMessageId();
                streamId      = MailUtil.CreateStreamId();
            }

            var fromAddress = MailUtil.CreateFullEmail(mbox.Name, mailAddress.Address);

            var draft = new MailDraftData(id, mbox, fromAddress, to, cc, bcc, subject, mimeMessageId, mimeReplyToId,
                                          importance, tags, body, streamId, attachments, calendarIcs)
            {
                FileLinksShareMode = fileLinksShareMode,
                PreviousMailboxId  = previousMailboxId,
                RequestReceipt     = requestReceipt,
                RequestRead        = requestRead,
                IsAutogenerated    = !string.IsNullOrEmpty(calendarIcs),
                IsAutoreplied      = isAutoreply
            };

            DaemonLabels = translates ?? DeliveryFailureMessageTranslates.Defauilt;

            return(Send(draft));
        }
Example #3
0
 private void BTNback_Click(object sender, RoutedEventArgs e)
 {
     MailUtil.BackRequest();
 }
Example #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)
        {
            if (!folderId.HasValue)
            {
                folderId = MailFolder.Ids.inbox;
            }

            if (folderId < MailFolder.Ids.inbox || folderId > MailFolder.Ids.spam)
            {
                throw new ArgumentException(@"Invalid folder id", "folderId");
            }

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

            var accounts = MailBoxManager.GetAccountInfo(TenantId, Username).ToAddressData();

            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 = MailBoxManager.GetUnremovedMailBox(account.MailboxId);

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

            var mimeMessageId = MailUtil.CreateMessageId();

            var restoreFolderId = folderId.Value == MailFolder.Ids.spam || folderId.Value == MailFolder.Ids.trash
                ? MailFolder.Ids.inbox
                : folderId.Value;

            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            = DateTime.UtcNow,
                MimeMessageId   = mimeMessageId,
                MimeReplyToId   = null,
                ChainId         = mimeMessageId,
                ReplyTo         = "",
                From            = MailUtil.CreateFullEmail(mbox.Name, mbox.EMail.Address),
                FromEmail       = mbox.EMail.Address,
                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 <MailAttachment>(),
                Size            = sampleBody.Length,
                MailboxId       = mbox.MailBoxId,
                HtmlBody        = sampleBody,
                Introduction    = sampleIntro,
                Folder          = folderId.Value,
                RestoreFolderId = restoreFolderId,
                IsNew           = unread,
                StreamId        = MailUtil.CreateStreamId()
            };

            MailBoxManager.StoreMailBody(mbox, sampleMessage);

            var id = MailBoxManager.MailSave(mbox, sampleMessage, 0, folderId.Value, restoreFolderId, SAMPLE_UIDL, "",
                                             false);

            return(id);
        }
        public void SendAutoreply(MailBoxData account, MailMessage message, string httpContextScheme, ILog log)
        {
            try
            {
                if (message.Folder != FolderType.Inbox ||
                    account.MailAutoreply == null ||
                    !account.MailAutoreply.TurnOn)
                {
                    return;
                }

                var utcNow = DateTime.UtcNow.Date;

                if (account.MailAutoreply.TurnOnToDate &&
                    account.MailAutoreply.ToDate != DateTime.MinValue &&
                    account.MailAutoreply.ToDate < utcNow)
                {
                    log.InfoFormat("DisableAutoreply(MailboxId = {0}) -> time is over", account.MailBoxId);

                    EnableAutoreply(account, false);

                    return;
                }

                if (account.MailAutoreply.FromDate > utcNow)
                {
                    log.Info("Skip MailAutoreply: FromDate > utcNow");
                    return;
                }

                if (account.MailAutoreply.FromDate > message.Date)
                {
                    log.Info("Skip MailAutoreply: FromDate > message.Date");
                    return;
                }

                if (MailUtil.IsMessageAutoGenerated(message))
                {
                    log.Info("Skip MailAutoreply: found some auto-generated header");
                    return;
                }

                if (IsCurrentMailboxInFrom(account, message))
                {
                    log.Info("Skip MailAutoreply: message from current account");
                    return;
                }

                var apiHelper = new ApiHelper(httpContextScheme);

                var autoreplyEmail = GetAutoreplyEmailInTo(account, message);

                if (string.IsNullOrEmpty(autoreplyEmail))
                {
                    log.Info("Skip MailAutoreply: autoreplyEmail not found");
                    return;
                }

                if (HasGroupsInTo(account, message))
                {
                    log.Info("Skip MailAutoreply: has group address in TO, CC");
                    return;
                }

                if (HasMailboxAutoreplyHistory(account, message.FromEmail))
                {
                    log.Info("Skip MailAutoreply: already sent to this address (history)");
                    return;
                }

                if (account.MailAutoreply.OnlyContacts && !apiHelper.SearchEmails(message.FromEmail).Any())
                {
                    log.Info("Skip MailAutoreply: message From address is not a part of user's contacts");
                    return;
                }

                apiHelper.SendMessage(CreateAutoreply(account, message, autoreplyEmail), true);
                account.MailAutoreplyHistory.Add(message.FromEmail);

                log.InfoFormat("AutoreplyEngine->SendAutoreply: auto-reply message has been sent to '{0}' email", autoreplyEmail);
            }
            catch (Exception ex)
            {
                log.ErrorFormat(
                    "AutoreplyEngine->SendAutoreply Error: {0}, innerException: {1}, account.MailBoxId = {2}, " +
                    "account.UserId = {3}, account.TenantId = {4}",
                    ex, ex.InnerException != null ? ex.InnerException.ToString() : string.Empty,
                    account.MailBoxId, account.UserId, account.TenantId);
            }
        }
Example #6
0
        private static void Main(string[] args)
        {
            XmlConfigurator.Configure();

            var options = new Options();

            if (!CommandLine.Parser.Default.ParseArgumentsStrict(args, options,
                                                                 () => Console.WriteLine("Bad command line parameters.")))
            {
                ShowAnyKey();
                return;
            }

            try
            {
                var reloadList = new Dictionary <int, List <int> >();

                if (!string.IsNullOrEmpty(options.PathToJson) && File.Exists(options.PathToJson))
                {
                    using (var streamReader = new StreamReader(options.PathToJson))
                    {
                        using (var reader = new JsonTextReader(streamReader))
                        {
                            var jObject = JObject.Load(reader);

                            if (jObject["data"] == null || !jObject["data"].Any())
                            {
                                Console.WriteLine("[ERROR] json tasks not found. Array is empty.");

                                ShowAnyKey();
                                return;
                            }

                            var results = jObject["data"].ToList().GroupBy(
                                p => Convert.ToInt32(p["id_mailbox"]),
                                p => Convert.ToInt32(p["id"]),
                                (key, g) => new { MailboxId = key, Ids = g.ToList() });

                            foreach (var result in results)
                            {
                                if (reloadList.ContainsKey(result.MailboxId))
                                {
                                    continue;
                                }

                                reloadList.Add(result.MailboxId, result.Ids);
                            }
                        }
                    }
                }
                else
                {
                    if (options.MailboxId < 0)
                    {
                        Console.WriteLine("[ERROR] MailboxId invalid.");

                        ShowAnyKey();
                        return;
                    }

                    if (options.MessageId < 0)
                    {
                        Console.WriteLine("[ERROR] MailboxId invalid.");

                        ShowAnyKey();
                        return;
                    }


                    reloadList.Add(options.MailboxId, new List <int> {
                        options.MessageId
                    });
                }

                foreach (var reloadItem in reloadList)
                {
                    MailClient client = null;

                    try
                    {
                        var mailboxId = reloadItem.Key;

                        Console.WriteLine("\r\nSearching account with id {0}", mailboxId);

                        var mailbox = GetMailBox(mailboxId);

                        if (mailbox == null)
                        {
                            Console.WriteLine("[ERROR] Account not found.");
                            ShowAnyKey();
                            return;
                        }

                        var messageIds = reloadItem.Value;

                        foreach (var messageId in messageIds)
                        {
                            Console.WriteLine("\r\nSearching message with id {0}", messageId);

                            if (messageId < 0)
                            {
                                Console.WriteLine("[ERROR] MessageId not setup.");
                                continue;
                            }

                            var storedMessage = GetMail(mailbox, messageId);

                            if (storedMessage == null)
                            {
                                Console.WriteLine("[ERROR] Message not found.");
                                continue;
                            }

                            var messageUid = storedMessage.Uidl;

                            if (mailbox.Imap)
                            {
                                var uidlStucture = ParserImapUidl(messageUid);
                                if (uidlStucture.folderId != MailFolder.Ids.inbox)
                                {
                                    Console.WriteLine("Only inbox messages are supported for downloading.");
                                    continue;
                                }
                            }

                            var certificatePermit = ConfigurationManager.AppSettings["mail.certificate-permit"] !=
                                                    null &&
                                                    Convert.ToBoolean(
                                ConfigurationManager.AppSettings["mail.certificate-permit"]);

                            var log = new NullLogger();

                            if (client == null)
                            {
                                client = new MailClient(mailbox, CancellationToken.None,
                                                        certificatePermit: certificatePermit);
                            }

                            MimeMessage mimeMessage;

                            try
                            {
                                mimeMessage = client.GetInboxMessage(messageUid);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("[ERROR] Failed GetInboxMessage(\"{0}\") Exception: {1}", messageUid, e);
                                continue;
                            }

                            var message = ConvertToMailMessage(mimeMessage,
                                                               new MailFolder(MailFolder.Ids.inbox, ""),
                                                               storedMessage.IsNew, storedMessage.ChainId, storedMessage.StreamId, log);

                            if (message == null)
                            {
                                Console.WriteLine("[ERROR] Failed ConvertToMailMessage(\"{0}\")", messageUid);
                                continue;
                            }

                            if (!storedMessage.From.Equals(MailUtil.NormalizeStringForMySql(message.From)) ||
                                !storedMessage.To.Equals(MailUtil.NormalizeStringForMySql(message.To)) ||
                                !storedMessage.Subject.Equals(MailUtil.NormalizeStringForMySql(message.Subject)))
                            {
                                Console.WriteLine("storedMessage.From = '{0}'", storedMessage.From);
                                Console.WriteLine("message.From = '{0}'",
                                                  MailUtil.NormalizeStringForMySql(message.From));

                                Console.WriteLine("storedMessage.To = '{0}'", storedMessage.To);
                                Console.WriteLine("message.To = '{0}'",
                                                  MailUtil.NormalizeStringForMySql(message.To));

                                Console.WriteLine("storedMessage.Subject = '{0}'", storedMessage.Subject);
                                Console.WriteLine("message.Subject = '{0}'",
                                                  MailUtil.NormalizeStringForMySql(message.Subject));

                                Console.WriteLine("[ERROR] Stored message not equals to server message");
                                continue;
                            }

                            if (storedMessage.Attachments.Any() && message.Attachments.Any())
                            {
                                var newAttachments = new List <MailAttachment>();

                                foreach (var attachment in message.Attachments)
                                {
                                    var storedAttachment =
                                        storedMessage.Attachments.FirstOrDefault(
                                            a =>
                                            (!string.IsNullOrEmpty(a.fileName) &&
                                             a.fileName.Equals(attachment.fileName,
                                                               StringComparison.InvariantCultureIgnoreCase)) ||
                                            !string.IsNullOrEmpty(a.contentId) &&
                                            a.contentId.Equals(attachment.contentId,
                                                               StringComparison.InvariantCultureIgnoreCase) ||
                                            !string.IsNullOrEmpty(a.contentLocation) &&
                                            a.contentLocation.Equals(attachment.contentLocation,
                                                                     StringComparison.InvariantCultureIgnoreCase));

                                    if (storedAttachment == null)
                                    {
                                        continue;
                                    }

                                    attachment.fileName   = storedAttachment.fileName;
                                    attachment.storedName = storedAttachment.storedName;
                                    attachment.fileNumber = storedAttachment.fileNumber;
                                    attachment.streamId   = storedAttachment.streamId;
                                    attachment.mailboxId  = storedAttachment.mailboxId;
                                    attachment.tenant     = storedAttachment.tenant;
                                    attachment.user       = storedAttachment.user;

                                    newAttachments.Add(attachment);
                                }

                                message.Attachments = newAttachments;
                            }

                            if (!TryStoreMailData(message, mailbox, log))
                            {
                                Console.WriteLine("[ERROR] Failed to store mail data");
                                continue;
                            }

                            Console.WriteLine("[SUCCESS] Mail \"{0}\" data was reloaded", messageId);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                    finally
                    {
                        if (client != null)
                        {
                            client.Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            ShowAnyKey();
        }
        public static MailMessage CreateMailMessage(this MimeMessage message,
                                                    int folder      = 1,
                                                    bool unread     = false,
                                                    string chainId  = "",
                                                    string streamId = "",
                                                    ILogger log     = null)
        {
            var mail = new MailMessage();

            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            log = log ?? new NullLogger();

            mail.Date          = MailUtil.IsDateCorrect(message.Date.UtcDateTime) ? message.Date.UtcDateTime : DateTime.UtcNow;
            mail.MimeMessageId = (string.IsNullOrEmpty(message.MessageId) ? MailUtil.CreateMessageId() : message.MessageId)
                                 .Trim(new[] { '<', '>' });
            mail.ChainId       = string.IsNullOrEmpty(chainId) ? mail.MimeMessageId : chainId;
            mail.MimeReplyToId = mail.ChainId.Equals(mail.MimeMessageId) || string.IsNullOrEmpty(message.InReplyTo)
                ? null
                : message.InReplyTo.Trim('<', '>');
            mail.ReplyTo   = message.ReplyTo.ToString();
            mail.From      = message.From.ToString();
            mail.FromEmail = message.From != null && message.From.Mailboxes != null && message.From.Mailboxes.Any()
                ? message.From.Mailboxes.First().Address
                : "";
            mail.ToList    = message.To.Mailboxes.Select(s => new MailAddress(s.Address, s.Name)).ToList();
            mail.To        = string.Join(", ", message.To.Mailboxes.Select(s => s.ToString()));
            mail.CcList    = message.Cc.Mailboxes.Select(s => new MailAddress(s.Address, s.Name)).ToList();
            mail.Cc        = string.Join(", ", message.Cc.Mailboxes.Select(s => s.ToString()));
            mail.Bcc       = string.Join(", ", message.Bcc.Mailboxes.Select(s => s.ToString()));
            mail.Subject   = message.Subject ?? string.Empty;
            mail.Important = message.Importance == MessageImportance.High || message.Priority == MessagePriority.Urgent;

            mail.TextBodyOnly = false;

            mail.Introduction = "";

            mail.Attachments = new List <MailAttachment>();

            mail.HtmlBodyStream = new MemoryStream();

            mail.ExtractMainParts(message);

            mail.Size = mail.HtmlBodyStream.Length > 0 ? mail.HtmlBodyStream.Length : mail.HtmlBody.Length;

            mail.HeaderFieldNames = new NameValueCollection();

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

            mail.Folder   = folder;
            mail.IsNew    = unread;
            mail.StreamId = string.IsNullOrEmpty(streamId) ? MailUtil.CreateStreamId() : streamId;

            mail.LoadCalendarInfo(message, log);

            return(mail);
        }
Example #8
0
        public void UploadIcsToCalendar(MailBoxData mailBoxData, int calendarId, string calendarEventUid, string calendarIcs,
                                        string calendarCharset, string calendarContentType, string calendarEventReceiveEmail, string httpContextScheme)
        {
            try
            {
                if (string.IsNullOrEmpty(calendarEventUid) ||
                    string.IsNullOrEmpty(calendarIcs) ||
                    calendarContentType != "text/calendar")
                {
                    return;
                }

                var calendar = MailUtil.ParseValidCalendar(calendarIcs, Log);

                if (calendar == null)
                {
                    return;
                }

                var alienEvent = true;

                var organizer = calendar.Events[0].Organizer;

                if (organizer != null)
                {
                    var orgEmail = calendar.Events[0].Organizer.Value.ToString()
                                   .ToLowerInvariant()
                                   .Replace("mailto:", "");

                    if (orgEmail.Equals(calendarEventReceiveEmail))
                    {
                        alienEvent = false;
                    }
                }
                else
                {
                    throw new ArgumentException("calendarIcs.organizer is null");
                }

                if (alienEvent)
                {
                    if (calendar.Events[0].Attendees.Any(
                            a =>
                            a.Value.ToString()
                            .ToLowerInvariant()
                            .Replace("mailto:", "")
                            .Equals(calendarEventReceiveEmail)))
                    {
                        alienEvent = false;
                    }
                }

                if (alienEvent)
                {
                    return;
                }

                CoreContext.TenantManager.SetCurrentTenant(mailBoxData.TenantId);
                SecurityContext.AuthenticateMe(new Guid(mailBoxData.UserId));

                using (var ms = new MemoryStream(EncodingTools.GetEncodingByCodepageName(calendarCharset).GetBytes(calendarIcs)))
                {
                    var apiHelper = new ApiHelper(httpContextScheme, Log);
                    apiHelper.UploadIcsToCalendar(calendarId, ms, "calendar.ics", calendarContentType);
                }

                Log.Info("CalendarEngine->UploadIcsToCalendar() has been succeeded");
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("CalendarEngine->UploadIcsToCalendar with \r\n" +
                                "calendarId: {0}\r\n" +
                                "calendarEventUid: '{1}'\r\n" +
                                "calendarIcs: '{2}'\r\n" +
                                "calendarCharset: '{3}'\r\n" +
                                "calendarContentType: '{4}'\r\n" +
                                "calendarEventReceiveEmail: '{5}'\r\n" +
                                "Exception:\r\n{6}\r\n",
                                calendarId, calendarEventUid, calendarIcs, calendarCharset, calendarContentType,
                                calendarEventReceiveEmail, ex.ToString());
            }
        }
    private static void SendMailToCandidate(Object oObject)
    {
        logger.Info("start SendMailToCandidate + Controls_CandidateSetup");

        Object[] oObjectArr = (Object[])oObject;

        Exam oExam = oObjectArr[0] as Exam;
        Candidate oCandidate = oObjectArr[1] as Candidate;

        CandidateBO oCandidateBO = new CandidateBO();
        Result oResult = new Result();
        MailForCandidate oMailForCandidate = new MailForCandidate();

        /***************************send mail by  rakib***********/

        SmtpClient oSMTPClient = new SmtpClient();

        try
        {
            if (oCandidate.CandidateEmail.Length > 0)
            {
                //oResult = oCandidateBO.LoadMailForCandidate(typeof(MailForCandidate), "CofigurableXML\\MailForSendCandidate.xml");

                oResult = new MailUtil().LoadMail(typeof(MailForCandidate), "CofigurableXML\\MailForSendCandidate.xml");

                if (oResult.ResultIsSuccess)
                {
                    oMailForCandidate = (MailForCandidate)oResult.ResultObject;

                    oSMTPClient.Credentials = new NetworkCredential(WindowsLoginManager.csWindowsUserName, WindowsLoginManager.csWindowsPassword, WindowsLoginManager.csWindowsDomain);
                    oSMTPClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                    oSMTPClient.Host = ServerManager.csSMTPServerAddress;
                    oSMTPClient.Port = (int)EPortManager.SMTPport;

                    MailMessage oTempMailMessage = new MailMessage();
                    oTempMailMessage.From = new MailAddress(oMailForCandidate.From);
                    oTempMailMessage.To.Add(oCandidate.CandidateEmail);
                    oTempMailMessage.Body = oMailForCandidate.BodyStart
                                            + "<br/>Please appear before ["
                                            + oExam.ExamDateWithStartingTime.ToString()
                                            + "] For Exam:"
                                            + oExam.ExamName
                                            + "<br/>Your Login ID is: "
                                            + oCandidate.CandidateEmail
                                            + "<br/>Your Password is: "
                                            + oCandidate.CandidatePassword
                                            + "<br/>"
                                            + oMailForCandidate.BodyEnd;
                    oTempMailMessage.Subject = oMailForCandidate.Subject;
                    oTempMailMessage.IsBodyHtml = true;

                    oSMTPClient.Send(oTempMailMessage);
                }
                else
                {
                    //handle, if mail is not sent to candidate
                }
            }
        }
        catch (SmtpFailedRecipientException oEXFailedRecipent)
        {
            logger.Info("SmtpFailedRecipientException class:Controls_CandidateSetup method:SendMailToCandidate" + oEXFailedRecipent.Message);

            valueStatus = 0;
        }
        catch (SmtpException oExSMTP)
        {
            logger.Info("SmtpException class:Controls_CandidateSetup method:SendMailToCandidate" + oExSMTP.Message);

            valueStatus = 1;
        }
        finally
        {
            oSMTPClient = null;
        }

        /*********************end send mail by rakib*****************/

        logger.Info("end SendMailToCandidate + Controls_CandidateSetup");
    }
        private void ClientOnGetMessage(object sender, MailClientMessageEventArgs mailClientMessageEventArgs)
        {
            var log = _log;

            Stopwatch watch = null;

            if (_tasksConfig.CollectStatistics)
            {
                watch = new Stopwatch();
                watch.Start();
            }

            var failed = false;

            var mailbox = mailClientMessageEventArgs.Mailbox;

            try
            {
                var mimeMessage = mailClientMessageEventArgs.Message;
                var uid         = mailClientMessageEventArgs.MessageUid;
                var folder      = mailClientMessageEventArgs.Folder;
                var unread      = mailClientMessageEventArgs.Unread;
                var fromEmail   = mimeMessage.From.Mailboxes.FirstOrDefault();
                log = mailClientMessageEventArgs.Logger;

                log.Debug("ClientOnGetMessage MailboxId = {0}, Address = '{1}'",
                          mailbox.MailBoxId, mailbox.EMail);

                var manager = new MailBoxManager(log);

                var md5 =
                    string.Format("{0}|{1}|{2}|{3}",
                                  mimeMessage.From.Mailboxes.Any() ? mimeMessage.From.Mailboxes.First().Address : "",
                                  mimeMessage.Subject, mimeMessage.Date.UtcDateTime, mimeMessage.MessageId).GetMd5();

                var uidl = mailbox.Imap ? string.Format("{0}-{1}", uid, folder.FolderId) : uid;

                var fromThisMailBox = fromEmail != null &&
                                      fromEmail.Address.ToLowerInvariant()
                                      .Equals(mailbox.EMail.Address.ToLowerInvariant());

                var toThisMailBox =
                    mimeMessage.To.Mailboxes.Select(addr => addr.Address.ToLowerInvariant())
                    .Contains(mailbox.EMail.Address.ToLowerInvariant());

                log.Info(
                    @"Message: Subject: '{1}' Date: {2} Unread: {5} FolderId: {3} ('{4}') MimeId: '{0}' Uidl: '{6}' Md5: '{7}' To->From: {8} From->To: {9}",
                    mimeMessage.MessageId, mimeMessage.Subject, mimeMessage.Date, folder.FolderId, folder.Name, unread,
                    uidl, md5, fromThisMailBox, toThisMailBox);

                List <int> tagsIds = null;

                if (folder.Tags.Any())
                {
                    log.Debug("GetOrCreateTags()");

                    tagsIds = manager.GetOrCreateTags(mailbox.TenantId, mailbox.UserId, folder.Tags);
                }

                log.Debug("SearchExistingMessagesAndUpdateIfNeeded()");

                var found = manager.SearchExistingMessagesAndUpdateIfNeeded(mailbox, folder.FolderId, uidl, md5,
                                                                            mimeMessage.MessageId, fromThisMailBox, toThisMailBox, tagsIds);

                var needSave = !found;
                if (!needSave)
                {
                    return;
                }

                log.Debug("DetectChainId()");

                var chainId = manager.DetectChainId(mailbox, mimeMessage.MessageId, mimeMessage.InReplyTo,
                                                    mimeMessage.Subject);

                var streamId = MailUtil.CreateStreamId();

                log.Debug("Convert MimeMessage->MailMessage");

                MailMessage message;

                try
                {
                    message = mimeMessage.CreateMailMessage(folder.FolderId, unread, chainId, streamId, log);
                }
                catch (Exception ex)
                {
                    log.Error("Convert MimeMessage->MailMessage: Exception: {0}", ex.ToString());

                    log.Debug("Creating fake message with original MimeMessage in attachments");

                    message = mimeMessage.CreateCorruptedMesage(folder.FolderId, unread, chainId, streamId);
                }

                log.Debug("TryStoreMailData()");

                if (!TryStoreMailData(message, mailbox, log))
                {
                    failed = true;
                    return;
                }

                var folderRestoreId = folder.FolderId == MailFolder.Ids.spam ? MailFolder.Ids.inbox : folder.FolderId;

                log.Debug("MailSave()");

                var attempt = 1;

                while (attempt < 3)
                {
                    try
                    {
                        message.Id = manager.MailSave(mailbox, message, 0, folder.FolderId, folderRestoreId,
                                                      uidl, md5, true);

                        break;
                    }
                    catch (MySqlException exSql)
                    {
                        if (!exSql.Message.StartsWith("Deadlock found"))
                        {
                            throw;
                        }

                        if (attempt > 2)
                        {
                            throw;
                        }

                        log.Warn("[DEADLOCK] MailSave() try again (attempt {0}/2)", attempt);

                        attempt++;
                    }
                }

                log.Debug("DoOptionalOperations()");

                DoOptionalOperations(message, mimeMessage, mailbox, tagsIds, log);
            }
            catch (Exception ex)
            {
                log.Error("[ClientOnGetMessage] Exception:\r\n{0}\r\n", ex.ToString());

                failed = true;
            }
            finally
            {
                if (_tasksConfig.CollectStatistics && watch != null)
                {
                    watch.Stop();

                    LogStat(PROCESS_MESSAGE, mailbox, watch.Elapsed, failed);
                }
            }
        }
Example #11
0
        public void StoreAttachmentWithoutQuota(MailAttachment attachment)
        {
            try
            {
                if ((attachment.dataStream == null || attachment.dataStream.Length == 0) && (attachment.data == null || attachment.data.Length == 0))
                {
                    return;
                }

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

                var storage = MailDataStore.GetDataStore(Tenant);

                storage.QuotaController = null;

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

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

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

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

                var attachmentPath = MailStoragePathCombiner.GerStoredFilePath(attachment);

                if (attachment.data != null)
                {
                    using (var reader = new MemoryStream(attachment.data))
                    {
                        var uploadUrl = storage.Save(attachmentPath, reader, attachment.fileName);
                        attachment.storedFileUrl = MailStoragePathCombiner.GetStoredUrl(uploadUrl);
                    }
                }
                else
                {
                    var uploadUrl = storage.Save(attachmentPath, attachment.dataStream, attachment.fileName);
                    attachment.storedFileUrl = MailStoragePathCombiner.GetStoredUrl(uploadUrl);
                }
            }
            catch (Exception e)
            {
                _logger.Error("StoreAttachmentWithoutQuota(). filename: {0}, ctype: {1} Exception:\r\n{2}\r\n",
                              attachment.fileName,
                              attachment.contentType,
                              e.ToString());

                throw;
            }
        }
        private void ClientOnGetMessage(object sender, MailClientMessageEventArgs mailClientMessageEventArgs)
        {
            var log = _log;

            Stopwatch watch = null;

            if (_tasksConfig.CollectStatistics)
            {
                watch = new Stopwatch();
                watch.Start();
            }

            var failed = false;

            var mailbox = mailClientMessageEventArgs.Mailbox;

            try
            {
                var mimeMessage = mailClientMessageEventArgs.Message;
                var uid         = mailClientMessageEventArgs.MessageUid;
                var folder      = mailClientMessageEventArgs.Folder;
                var unread      = mailClientMessageEventArgs.Unread;
                var fromEmail   = mimeMessage.From.Mailboxes.FirstOrDefault();
                log = mailClientMessageEventArgs.Logger;

                log.Debug("ClientOnGetMessage MailboxId = {0}, Address = '{1}'",
                          mailbox.MailBoxId, mailbox.EMail);

                CoreContext.TenantManager.SetCurrentTenant(mailbox.TenantId);
                SecurityContext.AuthenticateMe(new Guid(mailbox.UserId));

                var manager = new MailBoxManager(log);

                var md5 =
                    string.Format("{0}|{1}|{2}|{3}",
                                  mimeMessage.From.Mailboxes.Any() ? mimeMessage.From.Mailboxes.First().Address : "",
                                  mimeMessage.Subject, mimeMessage.Date.UtcDateTime, mimeMessage.MessageId).GetMd5();

                var uidl = mailbox.Imap ? string.Format("{0}-{1}", uid, folder.FolderId) : uid;

                var fromThisMailBox = fromEmail != null &&
                                      fromEmail.Address.ToLowerInvariant()
                                      .Equals(mailbox.EMail.Address.ToLowerInvariant());

                var toThisMailBox =
                    mimeMessage.To.Mailboxes.Select(addr => addr.Address.ToLowerInvariant())
                    .Contains(mailbox.EMail.Address.ToLowerInvariant());

                log.Info(
                    @"Message: Subject: '{1}' Date: {2} Unread: {5} FolderId: {3} ('{4}') MimeId: '{0}' Uidl: '{6}' Md5: '{7}' To->From: {8} From->To: {9}",
                    mimeMessage.MessageId, mimeMessage.Subject, mimeMessage.Date, folder.FolderId, folder.Name, unread,
                    uidl, md5, fromThisMailBox, toThisMailBox);

                List <int> tagsIds = null;

                if (folder.Tags.Any())
                {
                    log.Debug("GetOrCreateTags()");

                    tagsIds = manager.GetOrCreateTags(mailbox.TenantId, mailbox.UserId, folder.Tags);
                }

                log.Debug("SearchExistingMessagesAndUpdateIfNeeded()");

                var found = manager.SearchExistingMessagesAndUpdateIfNeeded(mailbox, folder.FolderId, uidl, md5,
                                                                            mimeMessage.MessageId, fromThisMailBox, toThisMailBox, tagsIds);

                var needSave = !found;
                if (!needSave)
                {
                    return;
                }

                log.Debug("DetectChainId()");

                var chainId = manager.DetectChainId(mailbox, mimeMessage.MessageId, mimeMessage.InReplyTo,
                                                    mimeMessage.Subject);

                var streamId = MailUtil.CreateStreamId();

                log.Debug("Convert MimeMessage->MailMessage");

                var message = ConvertToMailMessage(mimeMessage, folder, unread, chainId, streamId, log);

                log.Debug("TryStoreMailData()");

                if (!TryStoreMailData(message, mailbox, log))
                {
                    failed = true;
                    return;
                }

                log.Debug("MailSave()");

                if (TrySaveMail(manager, mailbox, message, folder, uidl, md5, log))
                {
                    log.Debug("DoOptionalOperations->START");

                    DoOptionalOperations(message, mimeMessage, mailbox, tagsIds, log);
                }
                else
                {
                    failed = true;

                    if (manager.TryRemoveMailDirectory(mailbox, message.StreamId))
                    {
                        log.Info("Problem with mail proccessing(Account:{0}). Body and attachment have been deleted", mailbox.EMail);
                    }
                    else
                    {
                        throw new Exception("Can't delete mail folder with data");
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("[ClientOnGetMessage] Exception:\r\n{0}\r\n", ex.ToString());

                failed = true;
            }
            finally
            {
                if (_tasksConfig.CollectStatistics && watch != null)
                {
                    watch.Stop();

                    LogStat(PROCESS_MESSAGE, mailbox, watch.Elapsed, failed);
                }
            }
        }
        private async void DeleteMail(object param, DialogClosingEventArgs args)
        {
            if (!((bool)args.Parameter) || CurrentMail == null)
            {
                return;
            }

            string filepath = CurrentMail.FilePath;

            MailUtil.LoginInfo info = new MailUtil.LoginInfo
            {
                account = account.Account,
                passwd  = account.Password,
                site    = account.PopHost
            };
            try
            {
                Regex  regex    = new Regex(@"\w+@\w+.com-(\d+).mail.tmp");
                string indexstr = regex.Match(filepath).Groups[1].Value;
                uint   index    = UInt32.Parse(indexstr);
                Console.WriteLine("Delete mail whose index = " + index);

                MailUtil.del_mail(info, index);
                // delete corresponding mail tmp file
                if (File.Exists(filepath))
                {
                    File.Delete(filepath);
                }

                // index reduce 1 if mail's original index greater than deleted one's
                string dir = Path.Combine(Directory.GetCurrentDirectory(), account.Account);
                foreach (string f in Directory.GetFiles(dir))
                {
                    Group g = regex.Match(f).Groups[1];
                    uint  i = UInt32.Parse(g.Value);
                    if (i > index)
                    {
                        string newFile = String.Concat(f.Substring(0, g.Index), i - 1, f.Substring(g.Index + g.Length));
                        File.Move(Path.Combine(dir, f), Path.Combine(dir, newFile));
                    }
                }
                // Flush binding item list
                DisplayMailItems = GetMailItems(account);

                // show snackbar
                TipMessage    = "删除成功";
                IsSnackActive = true;
                await Task.Delay(3000);

                IsSnackActive = false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                // show snackbar
                TipMessage    = "删除失败";
                IsSnackActive = true;
                await Task.Delay(3000);

                IsSnackActive = false;
            }
        }
Example #14
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)
        {
            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, null,
                                                           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);
        }
    private void SendMailToListOfCandidate(List<CandidateForExam> oListOfCandidateForExamForGrid, int[] iArrCheck, Exam oExam)
    {
        try
        {
            Result oResult = new Result();
            MailForExtendCandidate oMailForExtendCandidate = new MailForExtendCandidate();

            //oResult = oCandidateBO.LoadMailForCandidate(typeof(MailForExtendCandidate), "CofigurableXML\\MailForExtendCandidate.xml");

            oResult = new MailUtil().LoadMail(typeof(MailForExtendCandidate), "CofigurableXML\\MailForExtendCandidate.xml");

            if (oResult.ResultIsSuccess)
            {
                oMailForExtendCandidate = (MailForExtendCandidate)oResult.ResultObject;

                for (int i = 0; i < iArrCheck.Length; i++)
                {
                    if (iArrCheck[i] == 1)
                    {
                        Object[] oObjArr = new Object[3];
                        oObjArr[0] = oExam;
                        oObjArr[1] = oListOfCandidateForExamForGrid[i].CandidateForExamCandidate;
                        oObjArr[2] = oMailForExtendCandidate;

                        object oObject = new object();
                        oObject = oObjArr;

                        ThreadPool.QueueUserWorkItem(new WaitCallback(SendMailToCandidate), oObject);
                    }
                }
            }
        }
        catch (Exception oEx)
        {

        }
    }
Example #16
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(id);
            }

            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);
        }
Example #17
0
        private void LoadCalendarInfo(MimeMessage message)
        {
            if (!message.BodyParts.Any())
            {
                return;
            }

            try
            {
                var calendarParts = message.BodyParts.Where(p => p.ContentType.IsMimeType("text", "calendar")).ToList();

                if (!calendarParts.Any())
                {
                    return;
                }

                foreach (var calendarPart in calendarParts)
                {
                    var p = calendarPart as TextPart;
                    if (p == null)
                    {
                        continue;
                    }

                    var ics = p.Text;

                    var calendar = MailUtil.ParseValidCalendar(ics);

                    if (calendar == null)
                    {
                        return;
                    }

                    if (calendar.Events[0].Organizer == null &&
                        calendar.Method.Equals("REPLY", StringComparison.OrdinalIgnoreCase))
                    {
                        // Fix reply organizer (Outlook style of Reply)
                        var toAddress = message.To.Mailboxes.FirstOrDefault();
                        if (toAddress != null)
                        {
                            calendar.Events[0].Organizer = new Organizer("mailto:" + toAddress.Address)
                            {
                                CommonName = string.IsNullOrEmpty(toAddress.Name)
                                    ? toAddress.Address
                                    : toAddress.Name
                            };

                            ics = MailUtil.SerializeCalendar(calendar);
                        }
                    }

                    CalendarUid           = calendar.Events[0].UID;
                    CalendarId            = -1;
                    CalendarEventIcs      = ics;
                    CalendarEventCharset  = string.IsNullOrEmpty(p.ContentType.Charset) ? Encoding.UTF8.HeaderName : p.ContentType.Charset;
                    CalendarEventMimeType = p.ContentType.MimeType;

                    var calendarExists =
                        message.Attachments
                        .Any(
                            attach =>
                    {
                        var subType = attach.ContentType.MediaSubtype.ToLower().Trim();

                        if (string.IsNullOrEmpty(subType) ||
                            (!subType.Equals("ics") &&
                             !subType.Equals("ical") &&
                             !subType.Equals("ifb") &&
                             !subType.Equals("icalendar") &&
                             !subType.Equals("calendar")))
                        {
                            return(false);
                        }

                        var icsTextPart = attach as TextPart;
                        string icsAttach;

                        if (icsTextPart != null)
                        {
                            icsAttach = icsTextPart.Text;
                        }
                        else
                        {
                            using (var stream = new MemoryStream())
                            {
                                p.ContentObject.DecodeTo(stream);
                                var bytes    = stream.ToArray();
                                var encoding = MailUtil.GetEncoding(p.ContentType.Charset);
                                icsAttach    = encoding.GetString(bytes);
                            }
                        }

                        var cal = MailUtil.ParseValidCalendar(icsAttach);

                        if (cal == null)
                        {
                            return(false);
                        }

                        return(CalendarUid == cal.Events[0].UID);
                    });

                    if (calendarExists)
                    {
                        continue;
                    }

                    if (calendarPart.ContentDisposition == null)
                    {
                        calendarPart.ContentDisposition = new ContentDisposition();
                    }

                    if (string.IsNullOrEmpty(calendarPart.ContentDisposition.FileName))
                    {
                        calendarPart.ContentDisposition.FileName = calendar.Method == "REQUEST"
                            ? "invite.ics"
                            : calendar.Method == "REPLY" ? "reply.ics" : "cancel.ics";
                    }

                    LoadAttachments(new List <MimeEntity> {
                        calendarPart
                    }, true);
                }
            }
            catch
            {
                // Ignore
            }
        }
        private static MimeEntity ToMimeMessageBody(MailDraftData draft)
        {
            string textBody;

            MailUtil.TryExtractTextFromHtml(draft.HtmlBody, out textBody);

            MultipartAlternative alternative = null;
            MimeEntity           body        = null;

            if (!string.IsNullOrEmpty(textBody))
            {
                var textPart = new TextPart("plain")
                {
                    Text = textBody,
                    ContentTransferEncoding = ContentEncoding.QuotedPrintable
                };

                if (!string.IsNullOrEmpty(draft.HtmlBody))
                {
                    alternative = new MultipartAlternative {
                        textPart
                    };
                    body = alternative;
                }
                else
                {
                    body = textPart;
                }
            }

            if (!string.IsNullOrEmpty(draft.HtmlBody))
            {
                var htmlPart = new TextPart("html")
                {
                    Text = draft.HtmlBody,
                    ContentTransferEncoding = ContentEncoding.QuotedPrintable
                };

                MimeEntity html;

                if (draft.AttachmentsEmbedded.Any())
                {
                    htmlPart.ContentTransferEncoding = ContentEncoding.Base64;

                    var related = new MultipartRelated
                    {
                        Root = htmlPart
                    };

                    related.Root.ContentId = null;

                    foreach (var emb in draft.AttachmentsEmbedded)
                    {
                        var linkedResource = ConvertToMimePart(emb, emb.contentId);
                        related.Add(linkedResource);
                    }

                    html = related;
                }
                else
                {
                    html = htmlPart;
                }

                if (alternative != null)
                {
                    alternative.Add(html);
                }
                else
                {
                    body = html;
                }
            }

            if (!string.IsNullOrEmpty(draft.CalendarIcs))
            {
                var calendarPart = new TextPart("calendar")
                {
                    Text = draft.CalendarIcs,
                    ContentTransferEncoding = ContentEncoding.QuotedPrintable
                };

                calendarPart.ContentType.Parameters.Add("method", draft.CalendarMethod);

                if (alternative != null)
                {
                    alternative.Add(calendarPart);
                }
                else
                {
                    body = calendarPart;
                }
            }


            if (draft.Attachments.Any() || !string.IsNullOrEmpty(draft.CalendarIcs))
            {
                var mixed = new Multipart("mixed");

                if (body != null)
                {
                    mixed.Add(body);
                }

                foreach (var att in draft.Attachments)
                {
                    var attachment = ConvertToMimePart(att);
                    mixed.Add(attachment);
                }

                if (!string.IsNullOrEmpty(draft.CalendarIcs))
                {
                    var filename = "calendar.ics";
                    switch (draft.CalendarMethod)
                    {
                    case Defines.ICAL_REQUEST:
                        filename = "invite.ics";
                        break;

                    case Defines.ICAL_REPLY:
                        filename = "reply.ics";
                        break;

                    case Defines.ICAL_CANCEL:
                        filename = "cancel.ics";
                        break;
                    }

                    var contentType = new ContentType("application", "ics");
                    contentType.Parameters.Add("method", draft.CalendarMethod);
                    contentType.Parameters.Add("name", filename);

                    var calendarResource = new MimePart(contentType)
                    {
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName = filename
                    };

                    var data = Encoding.UTF8.GetBytes(draft.CalendarIcs);

                    var ms = new MemoryStream(data);

                    calendarResource.Content = new MimeContent(ms);

                    mixed.Add(calendarResource);
                }

                body = mixed;
            }

            if (body != null)
            {
                return(body);
            }

            return(new TextPart("plain")
            {
                Text = string.Empty
            });
        }
        public static MailMessageData ToMailMessage(this MailComposeBase draft)
        {
            MailboxAddress fromVerified;

            if (string.IsNullOrEmpty(draft.From))
            {
                throw new DraftException(DraftException.ErrorTypes.EmptyField, "Empty email address in {0} field",
                                         DraftFieldTypes.From);
            }

            if (!MailboxAddress.TryParse(ParserOptions.Default, draft.From, out fromVerified))
            {
                throw new DraftException(DraftException.ErrorTypes.IncorrectField, "Incorrect email address",
                                         DraftFieldTypes.From);
            }

            if (string.IsNullOrEmpty(fromVerified.Name))
            {
                fromVerified.Name = draft.Mailbox.Name;
            }

            if (string.IsNullOrEmpty(draft.MimeMessageId))
            {
                throw new ArgumentException("MimeMessageId");
            }

            var messageItem = new MailMessageData
            {
                From                   = fromVerified.ToString(),
                FromEmail              = fromVerified.Address,
                To                     = string.Join(", ", draft.To.ToArray()),
                Cc                     = draft.Cc != null?string.Join(", ", draft.Cc.ToArray()) : "",
                                   Bcc = draft.Bcc != null?string.Join(", ", draft.Bcc.ToArray()) : "",
                                             Subject          = draft.Subject,
                                             Date             = DateTime.UtcNow,
                                             Important        = draft.Important,
                                             HtmlBody         = draft.HtmlBody,
                                             Introduction     = MailUtil.GetIntroduction(draft.HtmlBody),
                                             StreamId         = draft.StreamId,
                                             TagIds           = draft.Labels != null && draft.Labels.Count != 0 ? new List <int>(draft.Labels) : null,
                                             Size             = draft.HtmlBody.Length,
                                             MimeReplyToId    = draft.MimeReplyToId,
                                             MimeMessageId    = draft.MimeMessageId,
                                             IsNew            = false,
                                             Folder           = draft.Folder,
                                             ChainId          = draft.MimeMessageId,
                                             CalendarUid      = draft.CalendarEventUid,
                                             CalendarEventIcs = draft.CalendarIcs,
                                             MailboxId        = draft.Mailbox.MailBoxId
            };

            if (messageItem.Attachments == null)
            {
                messageItem.Attachments = new List <MailAttachmentData>();
            }

            draft.Attachments.ForEach(attachment =>
            {
                attachment.tenant = draft.Mailbox.TenantId;
                attachment.user   = draft.Mailbox.UserId;
            });

            messageItem.Attachments.AddRange(draft.Attachments);

            messageItem.HasAttachments = messageItem.Attachments.Count > 0;

            return(messageItem);
        }
        public static MailMessage CreateCorruptedMesage(this MimeMessage message,
                                                        int folder      = 1,
                                                        bool unread     = false,
                                                        string chainId  = "",
                                                        string streamId = "")
        {
            var mailMessage = new MailMessage
            {
                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 <MailAttachment>();

            MailUtil.SkipErrors(() =>
            {
                var mailAttach = new MailAttachment
                {
                    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);
        }
        /// <summary>
        /// 删除资料
        /// </summary>
        /// <param name="dataInfo"></param>
        /// <param name="workUser"></param>
        /// <returns></returns>
        public ReturnValueModel Delete(DocumentManager documentManager, WorkUser workUser)
        {
            ReturnValueModel rvm = new ReturnValueModel();

            var data = _rep.FirstOrDefault <DocumentManager>(s => s.Id == documentManager.Id);

            if (data == null)
            {
                rvm.Success = false;
                rvm.Msg     = "Invalid Id";
                return(rvm);
            }

            if (data.IsDeleted == 1)
            {
                rvm.Msg     = "This DataInfo has been deleted.";
                rvm.Success = true;
                return(rvm);
            }

            var approvalEnabled = _systemService.AdminApprovalEnabled; //是否启用审核

            if (approvalEnabled && (data.MediaType == 1 || data.MediaType == 3))
            {
                switch (data.IsCompleted ?? EnumComplete.AddedUnapproved)
                {
                case EnumComplete.Locked:
                    rvm.Success = false;
                    return(rvm);

                case EnumComplete.Approved:
                    data.IsCompleted = EnumComplete.WillDelete;      //将要删除(等待审核)
                    _rep.Update(data);
                    _rep.SaveChanges();
                    //待审核发送邮件提醒

                    if (IsSendMail == "1")
                    {
                        MailUtil.SendMeetMail(workUser?.User.ChineseName ?? "", "资料", data.Title)
                        .ContinueWith((previousTask) =>
                        {
                            bool rCount = previousTask.Result;
                        });

                        //MailUtil.SendMeetMail(workUser?.User.ChineseName ?? "", "资料", data.Title);
                    }
                    break;

                case EnumComplete.Reject:
                case EnumComplete.AddedUnapproved:
                case EnumComplete.UpdatedUnapproved:
                    //删除数据
                    if (!DocumentManagerDeletion(data, workUser))
                    {
                        rvm.Msg     = "fail";
                        rvm.Success = false;
                        return(rvm);
                    }
                    break;

                default:
                    rvm.Msg     = "This DataInfo can not be deleted at this time.";
                    rvm.Success = false;
                    return(rvm);
                }
            }
            else
            {
                //删除数据
                if (!DocumentManagerDeletion(data, workUser))
                {
                    rvm.Msg     = "fail";
                    rvm.Success = false;
                    return(rvm);
                }
            }

            rvm.Msg     = "success";
            rvm.Success = true;
            return(rvm);
        }
Example #22
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());
            }
        }
        /// <summary>
        /// 重新发送消息
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="maxFailCount"></param>
        /// <returns>是否成功</returns>
        private bool ResendEmail(BaseMessageQueueEntity entity, int maxFailCount = 5)
        {
            var result = false;

            if (entity.MessageType.Equals("Email", StringComparison.OrdinalIgnoreCase))
            {
                if (entity.FailCount >= maxFailCount)
                {
                    //发送失败超过5次,移动数据到MessageFailed表
                    var entityFailed = new BaseMessageFailedEntity
                    {
                        Source      = entity.Source,
                        MessageType = entity.MessageType,
                        Recipient   = entity.Recipient,
                        Subject     = entity.Subject,
                        Body        = entity.Body,
                        FailCount   = entity.FailCount,
                        CreateTime  = entity.CreateTime,
                        SortCode    = 1
                    };
                    //entityFailed.Error = "";
                    if (!string.IsNullOrWhiteSpace(new BaseMessageFailedManager(UserInfo).Add(entityFailed)))
                    {
                        //删除MessageQueue表中的数据
                        Delete(entity.Id);
                        RemoveCache();
                    }
                    result = false;
                }
                else
                {
                    if (MailUtil.Send(entity.Recipient, entity.Subject, entity.Body))
                    {
                        //发送成功,移动数据到MessageSucceed表
                        var entitySucceed = new BaseMessageSucceedEntity
                        {
                            Source      = entity.Source,
                            MessageType = entity.MessageType,
                            Recipient   = entity.Recipient,
                            Subject     = entity.Subject,
                            Body        = entity.Body,
                            CreateTime  = entity.CreateTime,
                            SortCode    = 1
                        };
                        if (!string.IsNullOrWhiteSpace(new BaseMessageSucceedManager(UserInfo).Add(entitySucceed)))
                        {
                            //删除MessageQueue表中的数据
                            Delete(entity.Id);
                            RemoveCache();
                            result = true;
                        }
                    }
                    else
                    {
                        //更新MessageQueue表中的失败次数
                        entity.FailCount = entity.FailCount + 1;
                        UpdateEntity(entity);
                    }
                }
            }
            return(result);
        }
Example #24
0
        private static MimeEntity ToMimeMessageBody(MailDraft draft)
        {
            var linkedResources = new AttachmentCollection(true);
            var attachments     = new AttachmentCollection();

            string textBody;

            MailUtil.TryExtractTextFromHtml(draft.HtmlBody, out textBody);

            MultipartAlternative multipartAlternative = null;
            MimeEntity           body = null;

            if (!string.IsNullOrEmpty(textBody))
            {
                var textPart = new TextPart("plain")
                {
                    Text = textBody,
                    ContentTransferEncoding = ContentEncoding.QuotedPrintable
                };

                if (!string.IsNullOrEmpty(draft.HtmlBody))
                {
                    multipartAlternative = new MultipartAlternative {
                        textPart
                    };
                    body = multipartAlternative;
                }
                else
                {
                    body = textPart;
                }
            }

            if (!string.IsNullOrEmpty(draft.HtmlBody))
            {
                var htmlPart = new TextPart("html")
                {
                    Text = draft.HtmlBody,
                    ContentTransferEncoding = ContentEncoding.QuotedPrintable
                };

                MimeEntity tempPart;

                if (draft.AttachmentsEmbedded.Any())
                {
                    var multipartRelated = new MultipartRelated
                    {
                        Root = htmlPart
                    };

                    foreach (var emb in draft.AttachmentsEmbedded)
                    {
                        MimeEntity linkedResource;

                        if (!emb.data.Any())
                        {
                            var s3Key = MailStoragePathCombiner.GerStoredFilePath(emb);

                            var contentType =
                                ContentType.Parse(string.IsNullOrEmpty(emb.contentType)
                                    ? MimeMapping.GetMimeMapping(emb.fileName)
                                    : emb.contentType);

                            using (var stream = StorageManager
                                                .GetDataStoreForAttachments(emb.tenant)
                                                .GetReadStream(s3Key))
                            {
                                linkedResource = linkedResources.Add(emb.fileName, stream, contentType);
                            }
                        }
                        else
                        {
                            linkedResource = linkedResources.Add(emb.fileName, emb.data);
                        }

                        linkedResource.ContentId = emb.contentId;

                        multipartRelated.Add(linkedResource);
                    }

                    tempPart = multipartRelated;
                }
                else
                {
                    tempPart = htmlPart;
                }

                if (multipartAlternative != null)
                {
                    multipartAlternative.Add(tempPart);
                }
                else
                {
                    body = tempPart;
                }
            }

            if (!string.IsNullOrEmpty(draft.CalendarIcs))
            {
                var calendarPart = new TextPart("calendar")
                {
                    Text = draft.CalendarIcs,
                    ContentTransferEncoding = ContentEncoding.QuotedPrintable
                };

                calendarPart.ContentType.Parameters.Add("method", draft.CalendarMethod);

                if (multipartAlternative != null)
                {
                    multipartAlternative.Add(calendarPart);
                }
                else
                {
                    body = calendarPart;
                }
            }


            if (draft.Attachments.Any() || !string.IsNullOrEmpty(draft.CalendarIcs))
            {
                var multipart = new Multipart("mixed");

                if (body != null)
                {
                    multipart.Add(body);
                }

                foreach (var att in draft.Attachments)
                {
                    MimeEntity attachmentResource;

                    if (!att.data.Any())
                    {
                        var s3Key = MailStoragePathCombiner.GerStoredFilePath(att);

                        using (var stream = StorageManager
                                            .GetDataStoreForAttachments(att.tenant)
                                            .GetReadStream(s3Key))
                        {
                            attachmentResource = attachments.Add(att.fileName, stream);
                        }
                    }
                    else
                    {
                        attachmentResource = attachments.Add(att.fileName, att.data);
                    }

                    multipart.Add(attachmentResource);
                }

                if (!string.IsNullOrEmpty(draft.CalendarIcs))
                {
                    var filename = "calendar.ics";
                    switch (draft.CalendarMethod)
                    {
                    case "REQUEST":
                        filename = "invite.ics";
                        break;

                    case "REPLY":
                        filename = "reply.ics";
                        break;

                    case "CANCEL":
                        filename = "cancel.ics";
                        break;
                    }

                    var contentType = new ContentType("application", "ics");
                    contentType.Parameters.Add("method", draft.CalendarMethod);
                    contentType.Parameters.Add("name", filename);

                    var data = Encoding.UTF8.GetBytes(draft.CalendarIcs);

                    var calendarResource = attachments.Add(filename, data, contentType);
                    multipart.Add(calendarResource);
                }

                body = multipart;
            }

            if (body != null)
            {
                return(body);
            }

            return(new TextPart("plain")
            {
                Text = string.Empty
            });
        }
Example #25
0
        public static void LoadCalendarInfo(this MailMessageData mail, MimeMessage message, ILog log = null)
        {
            if (!message.BodyParts.Any())
            {
                return;
            }

            log = log ?? new NullLog();

            try
            {
                var calendarParts = message.BodyParts.Where(p => p.ContentType.IsMimeType("text", "calendar")).ToList();

                if (!calendarParts.Any())
                {
                    return;
                }

                log.DebugFormat("LoadCalendarInfo found {0} calendars", calendarParts.Count);

                foreach (var calendarPart in calendarParts)
                {
                    var p = calendarPart as TextPart;
                    if (p == null)
                    {
                        continue;
                    }

                    var ics = p.Text;

                    var calendar = MailUtil.ParseValidCalendar(ics, log);

                    if (calendar == null)
                    {
                        continue;
                    }

                    if (calendar.Events[0].Organizer == null &&
                        calendar.Method.Equals(Defines.ICAL_REPLY, StringComparison.OrdinalIgnoreCase))
                    {
                        // Fix reply organizer (Outlook style of Reply)
                        var toAddress = message.To.Mailboxes.FirstOrDefault();
                        if (toAddress != null)
                        {
                            calendar.Events[0].Organizer = new Ical.Net.DataTypes.Organizer("mailto:" + toAddress.Address)
                            {
                                CommonName = string.IsNullOrEmpty(toAddress.Name)
                                    ? toAddress.Address
                                    : toAddress.Name
                            };

                            ics = MailUtil.SerializeCalendar(calendar);
                        }
                    }

                    mail.CalendarUid           = calendar.Events[0].Uid;
                    mail.CalendarId            = -1;
                    mail.CalendarEventIcs      = ics;
                    mail.CalendarEventCharset  = string.IsNullOrEmpty(p.ContentType.Charset) ? Encoding.UTF8.HeaderName : p.ContentType.Charset;
                    mail.CalendarEventMimeType = p.ContentType.MimeType;

                    log.DebugFormat("Calendar UID: {0} Method: {1} ics: {2}", mail.CalendarUid, calendar.Method, mail.CalendarEventIcs);

                    var calendarExists =
                        message.Attachments
                        .Any(
                            attach =>
                    {
                        var subType = attach.ContentType.MediaSubtype.ToLower().Trim();

                        if (string.IsNullOrEmpty(subType) ||
                            (!subType.Equals("ics") &&
                             !subType.Equals("ical") &&
                             !subType.Equals("ifb") &&
                             !subType.Equals("icalendar") &&
                             !subType.Equals("calendar")))
                        {
                            return(false);
                        }

                        var icsTextPart = attach as TextPart;
                        string icsAttach;

                        if (icsTextPart != null)
                        {
                            icsAttach = icsTextPart.Text;
                        }
                        else
                        {
                            using (var stream = new MemoryStream())
                            {
                                p.Content.DecodeTo(stream);
                                var bytes    = stream.ToArray();
                                var encoding = MailUtil.GetEncoding(p.ContentType.Charset);
                                icsAttach    = encoding.GetString(bytes);
                            }
                        }

                        var cal = MailUtil.ParseValidCalendar(icsAttach, log);

                        if (cal == null)
                        {
                            return(false);
                        }

                        return(mail.CalendarUid == cal.Events[0].Uid);
                    });

                    if (calendarExists)
                    {
                        log.Debug("Calendar exists as attachment");
                        continue;
                    }

                    if (calendarPart.ContentDisposition == null)
                    {
                        calendarPart.ContentDisposition = new ContentDisposition();
                    }

                    if (string.IsNullOrEmpty(calendarPart.ContentDisposition.FileName))
                    {
                        calendarPart.ContentDisposition.FileName = calendar.Method == Defines.ICAL_REQUEST
                            ? "invite.ics"
                            : calendar.Method == Defines.ICAL_REPLY ? "reply.ics" : "cancel.ics";
                    }

                    mail.LoadAttachments(new List <MimeEntity> {
                        calendarPart
                    }, true);
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat("LoadCalendarInfo() \r\n Exception: \r\n{0}\r\n", ex.ToString());
            }
        }
Example #26
0
        /// <summary>
        /// Search emails in Accounts, Mail, CRM, Peaople Contact System
        /// </summary>
        /// <param name="tenant">Tenant id</param>
        /// <param name="userName">User id</param>
        /// <param name="term">Search word</param>
        /// <param name="maxCountPerSystem">limit result per Contact System</param>
        /// <param name="timeout">Timeout in milliseconds</param>
        /// <param name="httpContextScheme"></param>
        /// <returns></returns>
        public List <string> SearchEmails(int tenant, string userName, string term, int maxCountPerSystem, string httpContextScheme, int timeout = -1)
        {
            var equality = new ContactEqualityComparer();
            var contacts = new List <string>();
            var userGuid = new Guid(userName);

            var watch = new Stopwatch();

            watch.Start();

            var apiHelper = new ApiHelper(httpContextScheme, Log);

            var taskList = new List <Task <List <string> > >()
            {
                Task.Run(() =>
                {
                    CoreContext.TenantManager.SetCurrentTenant(tenant);
                    SecurityContext.CurrentUser = userGuid;

                    var engine = new EngineFactory(tenant, userName);

                    var exp = new FullFilterContactsExp(tenant, userName, term, infoType: ContactInfoType.Email, orderAsc: true, limit: maxCountPerSystem);

                    var contactCards = engine.ContactEngine.GetContactCards(exp);

                    return((from contactCard in contactCards
                            from contactItem in contactCard.ContactItems
                            select
                            string.IsNullOrEmpty(contactCard.ContactInfo.ContactName)
                                ? contactItem.Data
                                : MailUtil.CreateFullEmail(contactCard.ContactInfo.ContactName, contactItem.Data))
                           .ToList());
                }),

                Task.Run(() =>
                {
                    CoreContext.TenantManager.SetCurrentTenant(tenant);
                    SecurityContext.CurrentUser = userGuid;

                    var engine = new EngineFactory(tenant, userGuid.ToString());
                    return(engine.AccountEngine.SearchAccountEmails(term));
                }),

                Task.Run(() =>
                {
                    CoreContext.TenantManager.SetCurrentTenant(tenant);
                    SecurityContext.CurrentUser = userGuid;

                    return(WebItemSecurity.IsAvailableForMe(WebItemManager.CRMProductID)
                        ? apiHelper.SearchCrmEmails(term, maxCountPerSystem)
                        : new List <string>());
                }),

                Task.Run(() =>
                {
                    CoreContext.TenantManager.SetCurrentTenant(tenant);
                    SecurityContext.CurrentUser = userGuid;

                    return(WebItemSecurity.IsAvailableForMe(WebItemManager.PeopleProductID)
                        ? apiHelper.SearchPeopleEmails(term, 0, maxCountPerSystem)
                        : new List <string>());
                })
            };

            try
            {
                var taskArray = taskList.ToArray <Task>();

                Task.WaitAll(taskArray, timeout);

                watch.Stop();
            }
            catch (AggregateException e)
            {
                watch.Stop();

                var errorText =
                    new StringBuilder("SearchEmails: \nThe following exceptions have been thrown by WaitAll():");

                foreach (var t in e.InnerExceptions)
                {
                    errorText
                    .AppendFormat("\n-------------------------------------------------\n{0}", t);
                }

                Log.Error(errorText.ToString());
            }

            contacts =
                taskList.Aggregate(contacts,
                                   (current, task) => !task.IsFaulted &&
                                   task.IsCompleted &&
                                   !task.IsCanceled
                        ? current.Concat(task.Result).ToList()
                        : current)
                .Distinct(equality)
                .ToList();

            Log.DebugFormat("SearchEmails (term = '{0}'): {1} sec / {2} items", term, watch.Elapsed.TotalSeconds, contacts.Count);

            return(contacts);
        }
Example #27
0
        public void TestMailUtilSendMail()
        {
            bool sendt = MailUtil.SendMail("*****@*****.**", "*****@*****.**", "Test", "Body", false);

            Assert.IsTrue(sendt);
        }
Example #28
0
        public MailMessage Save(
            int id,
            string from,
            List <string> to,
            List <string> cc,
            List <string> bcc,
            string mimeReplyToId,
            bool importance,
            string subject,
            List <int> tags,
            string body,
            List <MailAttachmentData> attachments,
            string calendarIcs,
            DeliveryFailureMessageTranslates translates = null)
        {
            var mailAddress = new MailAddress(from);

            var engine = new EngineFactory(Tenant, User);

            var accounts = engine.AccountEngine.GetAccountInfoList().ToAccountData();

            var account = accounts.FirstOrDefault(a => a.Email.ToLower().Equals(mailAddress.Address));

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

            if (account.IsGroup)
            {
                throw new InvalidOperationException("Saving emails from a group address is forbidden");
            }

            var mbox = engine.MailboxEngine.GetMailboxData(
                new СoncreteUserMailboxExp(account.MailboxId, Tenant, User));

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

            string mimeMessageId, streamId;

            var previousMailboxId = mbox.MailBoxId;

            if (id > 0)
            {
                var message = engine.MessageEngine.GetMessage(id, new MailMessage.Options
                {
                    LoadImages    = false,
                    LoadBody      = true,
                    NeedProxyHttp = Defines.NeedProxyHttp,
                    NeedSanitizer = false
                });

                if (message.Folder != FolderType.Draft)
                {
                    throw new InvalidOperationException("Saving emails is permitted only in the Drafts folder");
                }

                mimeMessageId = message.MimeMessageId;

                streamId = message.StreamId;

                foreach (var attachment in attachments)
                {
                    attachment.streamId = streamId;
                }

                previousMailboxId = message.MailboxId;
            }
            else
            {
                mimeMessageId = MailUtil.CreateMessageId();
                streamId      = MailUtil.CreateStreamId();
            }

            var fromAddress = MailUtil.CreateFullEmail(mbox.Name, mbox.EMail.Address);

            var draft = new MailDraftData(id, mbox, fromAddress, to, cc, bcc, subject, mimeMessageId, mimeReplyToId, importance,
                                          tags, body, streamId, attachments, calendarIcs)
            {
                PreviousMailboxId = previousMailboxId
            };

            DaemonLabels = translates ?? DeliveryFailureMessageTranslates.Defauilt;

            return(Save(draft));
        }
Example #29
0
        public long SendMessage(int id,
                                string from,
                                List <string> to,
                                List <string> cc,
                                List <string> bcc,
                                string mimeReplyToId,
                                bool importance,
                                string subject,
                                List <int> tags,
                                string body,
                                List <MailAttachment> attachments,
                                FileShare fileLinksShareMode,
                                string calendarIcs,
                                bool isAutoreply)
        {
            if (id < 1)
            {
                id = 0;
            }

            if (string.IsNullOrEmpty(from))
            {
                throw new ArgumentNullException("from");
            }

            if (!to.Any())
            {
                throw new ArgumentNullException("to");
            }

            var mailAddress = new MailAddress(from);
            var accounts    = MailBoxManager.GetAccountInfo(TenantId, Username).ToAddressData();
            var account     = accounts.FirstOrDefault(a => a.Email.ToLower().Equals(mailAddress.Address));

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

            if (account.IsGroup)
            {
                throw new InvalidOperationException("Sending emails from a group address is forbidden");
            }

            var mbox = MailBoxManager.GetUnremovedMailBox(account.MailboxId);

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

            if (!mbox.Enabled)
            {
                throw new InvalidOperationException("Sending emails from a disabled account is forbidden");
            }

            string mimeMessageId, streamId;

            var previousMailboxId = mbox.MailBoxId;

            if (id > 0)
            {
                var message = GetMessage(id, false, false, false);

                if (message.Folder != MailFolder.Ids.drafts)
                {
                    throw new InvalidOperationException("Sending emails is permitted only in the Drafts folder");
                }

                mimeMessageId = message.MimeMessageId;

                streamId = message.StreamId;

                foreach (var attachment in attachments)
                {
                    attachment.streamId = streamId;
                }

                previousMailboxId = message.MailboxId;
            }
            else
            {
                mimeMessageId = MailUtil.CreateMessageId();
                streamId      = MailUtil.CreateStreamId();
            }

            var fromAddress = MailUtil.CreateFullEmail(mbox.Name, mailAddress.Address);

            var draft = new MailDraft(id, mbox, fromAddress, to, cc, bcc, subject, mimeMessageId, mimeReplyToId, importance,
                                      tags, body, streamId, attachments, calendarIcs)
            {
                FileLinksShareMode = fileLinksShareMode,
                PreviousMailboxId  = previousMailboxId
            };

            try
            {
                Thread.CurrentThread.CurrentCulture   = CurrentCulture;
                Thread.CurrentThread.CurrentUICulture = CurrentCulture;

                var daemonLabels =
                    new DraftManager.DeliveryFailureMessageTranslates(
                        MailDaemonEmail,
                        MailApiResource.DeliveryFailureSubject,
                        MailApiResource.DeliveryFailureAutomaticMessage,
                        MailApiResource.DeliveryFailureMessageIdentificator,
                        MailApiResource.DeliveryFailureRecipients,
                        MailApiResource.DeliveryFailureRecommendations,
                        MailApiResource.DeliveryFailureBtn,
                        MailApiResource.DeliveryFailureFAQInformation,
                        MailApiResource.DeliveryFailureReason);

                var draftsManager = new DraftManager(MailBoxManager, Logger, daemonLabels, isAutoreply);

                return(draftsManager.Send(draft));
            }
            catch (DraftException ex)
            {
                string fieldName;

                switch (ex.FieldType)
                {
                case DraftFieldTypes.From:
                    fieldName = MailApiResource.FieldNameFrom;
                    break;

                case DraftFieldTypes.To:
                    fieldName = MailApiResource.FieldNameTo;
                    break;

                case DraftFieldTypes.Cc:
                    fieldName = MailApiResource.FieldNameCc;
                    break;

                case DraftFieldTypes.Bcc:
                    fieldName = MailApiResource.FieldNameBcc;
                    break;

                default:
                    fieldName = "";
                    break;
                }
                switch (ex.ErrorType)
                {
                case DraftException.ErrorTypes.IncorrectField:
                    throw new ArgumentException(MailApiResource.ErrorIncorrectEmailAddress.Replace("%1", fieldName));

                case DraftException.ErrorTypes.EmptyField:
                    throw new ArgumentException(MailApiResource.ErrorEmptyField.Replace("%1", fieldName));

                default:
                    throw;
                }
            }
        }
    private void SendMailToSystemUserForUpdateNotifiaction(List<SystemUser> oListSystemUser, int[] iArrCheck)
    {
        try
        {
            CandidateBO oCandidateBO = new CandidateBO();
            Result oResult = new Result();
            MailForSystemUserModification oMailForSystemUserModification = new MailForSystemUserModification();

            //oResult = oCandidateBO.LoadMailForCandidate(typeof(MailForSystemUserModification), "CofigurableXML\\MailForSystemUserModification.xml");

            oResult = new MailUtil().LoadMail(typeof(MailForSystemUserModification), "CofigurableXML\\MailForSystemUserModification.xml");

            if (oResult.ResultIsSuccess)
            {
                oMailForSystemUserModification = (MailForSystemUserModification)oResult.ResultObject;

                for (int i = 0; i < iArrCheck.Length; i++)
                {
                    if (iArrCheck[i] == 1)
                    {
                        object oObject = new object();

                        object[] oArr = new object[2];

                        oArr[0] = oListSystemUser[i];

                        oArr[1] = oMailForSystemUserModification;

                        oObject = oArr;

                        ThreadPool.QueueUserWorkItem(new WaitCallback(SendMailToSystemUser), oObject);
                    }
                }
            }
        }
        catch (Exception oEx)
        {

        }
    }
Example #31
0
        public MailMessage SaveMessage(int id,
                                       string from,
                                       List <string> to,
                                       List <string> cc,
                                       List <string> bcc,
                                       string mimeReplyToId,
                                       bool importance,
                                       string subject,
                                       List <int> tags,
                                       string body,
                                       List <MailAttachment> attachments,
                                       string calendarIcs)
        {
            if (id < 1)
            {
                id = 0;
            }

            if (string.IsNullOrEmpty(from))
            {
                throw new ArgumentNullException("from");
            }

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

            var mailAddress = new MailAddress(from);

            var accounts = MailBoxManager.GetAccountInfo(TenantId, Username).ToAddressData();

            var account = accounts.FirstOrDefault(a => a.Email.ToLower().Equals(mailAddress.Address));

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

            if (account.IsGroup)
            {
                throw new InvalidOperationException("Saving emails from a group address is forbidden");
            }

            var mbox = MailBoxManager.GetUnremovedMailBox(account.MailboxId);

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

            string mimeMessageId, streamId;

            var previousMailboxId = mbox.MailBoxId;

            if (id > 0)
            {
                var message = GetMessage(id, false, false, false);

                if (message.Folder != MailFolder.Ids.drafts)
                {
                    throw new InvalidOperationException("Saving emails is permitted only in the Drafts folder");
                }

                mimeMessageId = message.MimeMessageId;

                streamId = message.StreamId;

                foreach (var attachment in attachments)
                {
                    attachment.streamId = streamId;
                }

                previousMailboxId = message.MailboxId;
            }
            else
            {
                mimeMessageId = MailUtil.CreateMessageId();
                streamId      = MailUtil.CreateStreamId();
            }

            var fromAddress = MailUtil.CreateFullEmail(mbox.Name, mbox.EMail.Address);

            var draft = new MailDraft(id, mbox, fromAddress, to, cc, bcc, subject, mimeMessageId, mimeReplyToId, importance,
                                      tags, body, streamId, attachments, calendarIcs)
            {
                PreviousMailboxId = previousMailboxId
            };

            try
            {
                var draftsManager = new DraftManager(MailBoxManager, Logger);

                return(draftsManager.Save(draft));
            }
            catch (DraftException ex)
            {
                string fieldName;

                switch (ex.FieldType)
                {
                case DraftFieldTypes.From:
                    fieldName = MailApiResource.FieldNameFrom;
                    break;

                default:
                    fieldName = "";
                    break;
                }
                switch (ex.ErrorType)
                {
                case DraftException.ErrorTypes.IncorrectField:
                    throw new ArgumentException(MailApiResource.ErrorIncorrectEmailAddress.Replace("%1", fieldName));

                case DraftException.ErrorTypes.EmptyField:
                    throw new ArgumentException(MailApiResource.ErrorEmptyField.Replace("%1", fieldName));

                default:
                    throw;
                }
            }
        }
    private static void SendMailToSystemUser(Object oObject)
    {
        logger.Info("start SendMailToSystemUser + Controls_SystemUserEntry");

        Object[] oObjectArr = (Object[])oObject;

        SystemUser oSystemUser = oObjectArr[0] as SystemUser;

        CandidateBO oCandidateBO = new CandidateBO();
        Result oResult = new Result();
        MailForSystemUserEntry oMailForSystemUserEntry = new MailForSystemUserEntry();

        SmtpClient oSMTPClient = new SmtpClient();

        try
        {
            if (oSystemUser.SystemUserEmail.Length > 0)
            {
                //oResult = oCandidateBO.LoadMailForCandidate(typeof(MailForSystemUserEntry), "CofigurableXML\\MailForSystemUserEntry.xml");

                oResult = new MailUtil().LoadMail(typeof(MailForSystemUserEntry), "CofigurableXML\\MailForSystemUserEntry.xml");

                if (oResult.ResultIsSuccess)
                {
                    oMailForSystemUserEntry = (MailForSystemUserEntry)oResult.ResultObject;

                    oSMTPClient.Credentials = new NetworkCredential(WindowsLoginManager.csWindowsUserName, WindowsLoginManager.csWindowsPassword, WindowsLoginManager.csWindowsDomain);
                    oSMTPClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                    oSMTPClient.Host = ServerManager.csSMTPServerAddress;
                    oSMTPClient.Port = (int)EPortManager.SMTPport;

                    MailMessage oTempMailMessage = new MailMessage();
                    oTempMailMessage.From = new MailAddress(oMailForSystemUserEntry.From);
                    oTempMailMessage.To.Add(oSystemUser.SystemUserEmail);
                    oTempMailMessage.Body = oMailForSystemUserEntry.BodyStart
                                            + "<br/>Your Login ID is: "
                                            + oSystemUser.SystemUserName
                                            + "<br/>Your Password is: "
                                            + oSystemUser.SystemUserPassword
                                            + "<br/>"
                                            + oMailForSystemUserEntry.BodyEnd;
                    oTempMailMessage.Subject = oMailForSystemUserEntry.Subject;
                    oTempMailMessage.IsBodyHtml = true;

                    oSMTPClient.Send(oTempMailMessage);
                }
                else
                {
                    //handle, if mail is not sent to candidate
                }
            }
        }
        catch (SmtpFailedRecipientException oEXFailedRecipent)
        {
            logger.Info("SmtpFailedRecipientException class:Controls_SystemUserEntry method:SendMailToSystemUser" + oEXFailedRecipent.Message);

            valueStatus = 0;
        }
        catch (SmtpException oExSMTP)
        {
            logger.Info("SmtpException class:Controls_SystemUserEntry method:SendMailToSystemUser" + oExSMTP.Message);

            valueStatus = 1;
        }
        finally
        {
            oSMTPClient = null;
        }

        logger.Info("end SendMailToSystemUser + Controls_SystemUserEntry");
    }
Example #33
0
        private void btGerarPlanilha_Click(object sender, EventArgs e)
        {
            btGerarPlanilha.Enabled = false;

            DataTable deta = new DataTable("MDTD");

            deta.Columns.Add("CodigoAgenteCustodia", typeof(System.String));
            deta.Columns.Add("CodigoCliente", typeof(System.String));
            deta.Columns.Add("DigitoCodigoCliente", typeof(System.String));
            deta.Columns.Add("CpfCpnjCliente", typeof(System.String));
            deta.Columns.Add("TipoTitulo", typeof(System.String));
            deta.Columns.Add("DataVctoTitulo", typeof(System.String));
            deta.Columns.Add("CodigoSelic", typeof(System.String));
            deta.Columns.Add("CodigoISIN", typeof(System.String));
            deta.Columns.Add("TipoTransacao", typeof(System.String));
            deta.Columns.Add("IDContabilTransacao", typeof(System.String));
            deta.Columns.Add("QuantitadeTitulosTransacao", typeof(System.String));
            deta.Columns.Add("NumeroProtocolo", typeof(System.String));
            deta.Columns.Add("Usuario", typeof(System.String));
            deta.Columns.Add("AgenteCustodiaContraparte", typeof(System.String));
            deta.Columns.Add("PrecoUnitarioTransacao", typeof(System.String));
            deta.Columns.Add("ValorTransacao", typeof(System.String));
            deta.Columns.Add("ValorTaxaAgente", typeof(System.String));
            deta.Columns.Add("ValorTotal", typeof(System.String));
            deta.Columns.Add("PrecoUnitarioOriginal", typeof(System.String));
            deta.Columns.Add("ValorOriginal", typeof(System.String));
            deta.Columns.Add("DataPrecoOriginal", typeof(System.String));
            deta.Columns.Add("OrigemSaldo", typeof(System.String));
            deta.Columns.Add("DataOperacao", typeof(System.String));
            deta.Columns.Add("DataMovimento", typeof(System.String));
            deta.Columns.Add("DataFinalDoacaoCupom", typeof(System.String));
            deta.Columns.Add("ValorTxSemBMFBovespa", typeof(System.String));
            deta.Columns.Add("ValorTxSemAgenteCustodia", typeof(System.String));
            deta.Columns.Add("PercentualReinvestimento", typeof(System.String));
            deta.Columns.Add("ProtocoloAgendamento", typeof(System.String));
            deta.Columns.Add("DataEmissaoTitulo", typeof(System.String));
            deta.Columns.Add("DataPagtoCupomAnterior", typeof(System.String));
            deta.Columns.Add("DataPagtoPrimeiroCupom", typeof(System.String));
            deta.Columns.Add("PUPrimeiroCupomJurosPago", typeof(System.String));
            deta.Columns.Add("DataPgtoCupomAnteriorCompra", typeof(System.String));
            deta.Columns.Add("DataLiquidacaoCompra", typeof(System.String));
            deta.Columns.Add("Filler", typeof(System.String));

            deta.AcceptChanges();



            //try
            //{
            logger.Info("Inicio processamento arquivo MDTD_01_IDENTIFICACAO_X");

            string[] lines = File.ReadAllLines(arquivo);

            long tamstrut = Marshal.SizeOf(typeof(MDTD_01_IDENTIFICACAO_X));

            foreach (string line in lines)
            {
                string tipo     = line.Substring(0, 2);
                string registro = line.Substring(2);

                if (tipo.Equals("01"))
                {
                    DataRow row = deta.NewRow();

                    MDTD_01_IDENTIFICACAO_X strut = Utilities.MarshalFromStringBlock <MDTD_01_IDENTIFICACAO_X>(line);

                    row["CodigoAgenteCustodia"]       = Convert.ToInt32(strut.CodigoAgenteCustodia.ByteArrayToString()).ToString();
                    row["CodigoCliente"]              = Convert.ToInt32(strut.CodigoCliente.ByteArrayToString()).ToString();
                    row["DigitoCodigoCliente"]        = Convert.ToInt32(strut.DigitoCodigoCliente.ByteArrayToString()).ToString();
                    row["CpfCpnjCliente"]             = strut.CpfCpnjCliente.ByteArrayToString();
                    row["TipoTitulo"]                 = strut.TipoTitulo.ByteArrayToString();
                    row["DataVctoTitulo"]             = strut.DataVctoTitulo.ByteArrayToString();
                    row["CodigoSelic"]                = strut.CodigoSelic.ByteArrayToString();
                    row["CodigoISIN"]                 = strut.CodigoISIN.ByteArrayToString();
                    row["TipoTransacao"]              = strut.TipoTransacao.ByteArrayToString();
                    row["IDContabilTransacao"]        = strut.IDContabilTransacao.ByteArrayToString();
                    row["QuantitadeTitulosTransacao"] = strut.QuantitadeTitulosTransacao.ByteArrayToDecimal(2).ToString();
                    row["NumeroProtocolo"]            = strut.NumeroProtocolo.ByteArrayToString();
                    row["Usuario"] = strut.Usuario.ByteArrayToString();
                    row["AgenteCustodiaContraparte"] = strut.CodigoAgenteCustodia.ByteArrayToString().ToString();
                    row["PrecoUnitarioTransacao"]    = strut.PrecoUnitarioTransacao.ByteArrayToDecimal(2).ToString();
                    row["ValorTransacao"]            = strut.ValorTransacao.ByteArrayToDecimal(2).ToString();
                    row["ValorTaxaAgente"]           = strut.ValorTaxaAgente.ByteArrayToDecimal(2).ToString();
                    row["ValorTotal"]                  = strut.ValorTotal.ByteArrayToDecimal(2).ToString();
                    row["PrecoUnitarioOriginal"]       = Convert.ToInt32(strut.PrecoUnitarioOriginal.ByteArrayToDecimal(2)).ToString();
                    row["ValorOriginal"]               = strut.ValorOriginal.ByteArrayToDecimal(2).ToString();
                    row["DataPrecoOriginal"]           = strut.DataPrecoOriginal.ByteArrayToString();
                    row["OrigemSaldo"]                 = strut.OrigemSaldo.ByteArrayToString();
                    row["DataOperacao"]                = strut.DataOperacao.ByteArrayToString();
                    row["DataMovimento"]               = strut.DataMovimento.ByteArrayToString();
                    row["DataFinalDoacaoCupom"]        = strut.DataFinalDoacaoCupom.ByteArrayToString();
                    row["ValorTxSemBMFBovespa"]        = strut.ValorTxSemBMFBovespa.ByteArrayToDecimal(2).ToString();
                    row["ValorTxSemAgenteCustodia"]    = strut.ValorTxSemAgenteCustodia.ByteArrayToDecimal(2).ToString();
                    row["PercentualReinvestimento"]    = strut.PercentualReinvestimento.ByteArrayToString();
                    row["ProtocoloAgendamento"]        = strut.ProtocoloAgendamento.ByteArrayToString();
                    row["DataEmissaoTitulo"]           = strut.DataEmissaoTitulo.ByteArrayToString();
                    row["DataPagtoCupomAnterior"]      = strut.DataPagtoCupomAnterior.ByteArrayToString();
                    row["DataPagtoPrimeiroCupom"]      = strut.DataPagtoPrimeiroCupom.ByteArrayToString();
                    row["PUPrimeiroCupomJurosPago"]    = strut.PUPrimeiroCupomJurosPago.ByteArrayToDecimal(2).ToString();
                    row["DataPgtoCupomAnteriorCompra"] = strut.DataPgtoCupomAnteriorCompra.ByteArrayToString();
                    row["DataLiquidacaoCompra"]        = strut.DataLiquidacaoCompra.ByteArrayToString();
                    row["Filler"] = strut.Filler.ByteArrayToString();

                    deta.Rows.Add(row);
                }
            }

            DataSet ds1 = new DataSet("DS1");

            ds1.Tables.Add(deta);
            ds1.AcceptChanges();

            if (ExcelCreator.CreateExcel(ds1, excelFile, "Sheet1"))
            {
                logger.Info("Movimento Diario Tesouro Direto planilha gerada com sucesso");


                string subject = " Movimento Diario Tesouro Direto - " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");

                string message = "Planilha Movimento Diario Tesouro Direto gerada as " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
                message += "\n\n";
                message += "Gravado em [" + excelFile + "]";

                if (!String.IsNullOrEmpty(rede))
                {
                    message += "\n\n";

                    message += "Disponivel na pasta de rede: [" + rede + "]";
                }


                //if (!String.IsNullOrEmpty(parametros.Message))
                //{
                //    message += "\n\n" + parametros.Message;
                //}

                message += "\n\n";

                string[] anexos = new string[1];
                anexos[0] = excelFile;

                MailUtil.EnviarPlanilhaPorEmail("*****@*****.**",
                                                "*****@*****.**",
                                                null,
                                                null,
                                                subject,
                                                message,
                                                anexos);
            }

            //try
            //{
            //    if (!String.IsNullOrEmpty(rede))
            //    {
            //        FileInfo excelInfo = new FileInfo(excelFile);
            //        rede += Path.DirectorySeparatorChar;
            //        rede += excelInfo.Name;

            //        logger.Info("GenerateVctosRendaFixa(" + functionName + ") Copiando arquivo [" + excelFile + "] para [" + rede + "]");
            //        File.Copy(excelFile, rede);
            //    }
            //    else
            //        logger.Info("GenerateVctosRendaFixa(" + functionName + ") Chave appsettings 'DiretorioRede' nao existe para copia do arquivo!");
            //}
            //catch (Exception ex)
            //{
            //    logger.Error("GenerateVctosRendaFixa(" + functionName + "): Erro ao copiar para pasta de rede");
            //    logger.Error("GenerateVctosRendaFixa(" + functionName + "): " + ex.Message, ex);
            //}
            //}
            //catch (Exception ex)
            //{
            //    logger.Error("_processa_ItauFJ_03_Cotacoes(): " + ex.Message, ex);
            //}

            btGerarPlanilha.Enabled = true;
        }