Exemple #1
0
        /// <summary>
        /// Gets the attachment.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="cid">The cid.</param>
        /// <returns></returns>
        public static MimeEntry GetAttachment(MimeEntryCollection MimeEntries, string cid)
        {
            foreach (MimeEntry entry in MimeEntries)
            {
                string ContentID = entry.Headers["Content-ID"];
                if (ContentID != null)
                {
                    if (ContentID.IndexOf(cid) != -1)
                    {
                        return(entry);
                    }
                }

                if (entry.MimeEntries.Count > 0)
                {
                    MimeEntry retVal = GetAttachment(entry.MimeEntries, cid);
                    if (retVal != null)
                    {
                        return(retVal);
                    }
                }
            }

            return(null);
        }
Exemple #2
0
            public static AttachmentData Create(MimeEntry entry)
            {
                AttachmentData retVal = new AttachmentData();

                retVal.ContentType = entry.ContentType;
                retVal.FileName    = EMailMessageInfo.GetFileName(entry);
                retVal.Data        = entry.Body;

                return(retVal);
            }
Exemple #3
0
        private static string ConstructMultiPart(MimeEntry ent, bool bodystructure)
        {
            string str = "(";

            str += ConstructPart(ent.MimeEntries, bodystructure);

            str += " ";

            // conentSubType
            if (ent.ContentType.Split('/').Length == 2)
            {
                str += "\"" + ent.ContentType.Split('/')[1].Replace(";", "") + "\"";
            }
            else
            {
                str += "NIL";
            }

            // Need to add extended fields
            if (bodystructure)
            {
                str += " ";

                // conentTypeSubFields
                string longContentType = MimeParser.ParseHeaderField("Content-Type:", ent.Headers);
                if (longContentType.IndexOf(";") > -1)
                {
                    str += "(";
                    string[] fields = longContentType.Split(';');
                    for (int i = 1; i < fields.Length; i++)
                    {
                        string[] nameValue = fields[i].Replace("\"", "").Trim().Split(new char[] { '=' }, 2);

                        str += "\"" + nameValue[0] + "\" \"" + nameValue[1] + "\"";

                        if (i < fields.Length - 1)
                        {
                            str += " ";
                        }
                    }
                    str += ") ";
                }

                // contentDisposition
                str += "NIL ";

                // contentLanguage
                str += "NIL";
            }

            str += ")";

            return(str);
        }
Exemple #4
0
        /// <summary>
        /// Gets the name of the file.
        /// </summary>
        /// <param name="entry">The entry.</param>
        /// <returns></returns>
        private static string GetFileName(MimeEntry entry)
        {
            string fileName = entry.FileName;

            if (fileName == null)
            {
                if (entry.ContentType != null)
                {
                    if (entry.ContentType == "message/rfc822")
                    {
                        fileName = "Attached.eml";
                    }
                    else
                    {
                        Hashtable parametrs = new Hashtable();

                        Regex contentParser = new Regex("(?<type>[^;]+)(;(\\s)*(?<parameter>((?<attribute>[^=]+)=(?<value>((\"[^\"]*\")?[^;]*)))))*");

                        Match match = contentParser.Match(entry.Headers["Content-Type"]);

                        string Type = match.Groups["type"].Value;

                        int CaptureLen = match.Groups["parameter"].Captures.Count;
                        for (int iIndex = 0; iIndex < CaptureLen; iIndex++)
                        {
                            parametrs[match.Groups["attribute"].Captures[iIndex].Value.ToLower()] = match.Groups["value"].Captures[iIndex].Value.Replace("\"", "");
                        }
                        fileName = (string)parametrs["name"];

                        // 2007-11-15 Try get default extension by ContentType
                        if (fileName == null)
                        {
                            using (System.Data.IDataReader reader = ContentType.GetContentTypeByString(entry.ContentType))
                            {
                                if (reader.Read())
                                {
                                    fileName = "Attached." + (string)reader["Extension"];
                                }
                            }
                        }
                    }
                }

                if (fileName == null)
                {
                    fileName = "Unknown.dat";
                }
            }
            return(fileName);
        }
Exemple #5
0
        protected void SaveMimeEntry(System.IO.StreamWriter writer, MimeEntry entry)
        {
            if (entry.ContentDisposition == Disposition.Attachment)
            {
                return;
            }

            // Step 2. Process Mime Entry [5/11/2004]

            string    ContentType          = entry.Headers["Content-Type"];
            Hashtable ContentTypeParametrs = ParseHeaderLine(ContentType);
            string    ContentTypeBoundary  = (string)ContentTypeParametrs["boundary"];

            //			if(ContentType==null)
            //				ContentType = "Content-Type: text/html; charset=\"utf-8\"";

            if (entry.Body != null && ContentTypeBoundary == null)
            {
                writer.Write("\r\n------=_NextPart_000_0000_01C26874.EA4F5D40\r\n");
                SaveHeaders(writer, entry.Headers);

                //				if(ContentType.IndexOf("text/html")!=-1)
                //				{
                //					writer.Write(Convert.ToBase64String(Encoding.UTF8.GetBytes(entry.BodyText)));
                //				}

                if (ContentType == null)
                {
                    ContentType = "Content-Type: text/html; charset=\"utf-8\"";
                    writer.Write(Convert.ToBase64String(Encoding.UTF8.GetBytes(entry.BodyText)));
                }
                else
                {
                    writer.Write(Convert.ToBase64String(entry.Body));
                }
            }

            foreach (MimeEntry childEntry in entry.MimeEntries)
            {
                SaveMimeEntry(writer, childEntry);
            }
        }
Exemple #6
0
        /// <summary>
        /// Returns requested mime entry data.
        /// </summary>
        /// <param name="parser"></param>
        /// <param name="mimeEntryNo"></param>
        /// <returns>Returns requested mime entry data or NULL if requested entri doesn't exist.</returns>
        public static byte[] ParseMimeEntry(MimeParser parser, string mimeEntryNo)
        {
            MimeEntry mEntry = null;

            string[] parts = mimeEntryNo.Split('.');
            foreach (string part in parts)
            {
                int mEntryNo = Convert.ToInt32(part);
                if (mEntry == null)
                {
                    if (mEntryNo > 0 && mEntryNo <= parser.MimeEntries.Count)
                    {
                        mEntry = ((MimeEntry)parser.MimeEntries[mEntryNo - 1]);
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    if (mEntryNo > 0 && mEntryNo <= mEntry.MimeEntries.Count)
                    {
                        mEntry = ((MimeEntry)mEntry.MimeEntries[mEntryNo - 1]);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }

            if (mEntry != null)
            {
                return(mEntry.DataNonDecoded);
            }
            else
            {
                return(null);
            }
        }
Exemple #7
0
        /// <summary>
        /// Pushes the embedded resource to web response.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="EMailMessageId">The E mail message id.</param>
        /// <param name="Cid">The cid.</param>
        public static void PushEmbeddedResourceToWebResponse(System.Web.HttpResponse response, int EMailMessageId, string Cid)
        {
            EMailMessageRow row = new EMailMessageRow(EMailMessageId);

            MemoryStream memStream = new MemoryStream(row.EmlMessage.Length);

            memStream.Write(row.EmlMessage, 0, row.EmlMessage.Length);
            memStream.Position = 0;

            ///////////////// Test
            // E:\Util\BlobDataExtractor\output24700.eml
            //System.IO.StreamReader st = new System.IO.StreamReader(@"D:\EMailMessage_55325.eml", System.Text.Encoding.Default);
            //string strmsg = st.ReadToEnd();
            //byte[] buffer = System.Text.Encoding.Default.GetBytes(strmsg);
            //System.IO.MemoryStream memStream = new System.IO.MemoryStream(buffer, 0, buffer.Length, true, true);
            /////////////////

            Pop3Message message = new Pop3Message(memStream);

            MimeEntry entry = GetAttachment(message.MimeEntries, Cid);

            if (entry == null)
            {
                //throw new HttpException(404, string.Empty);
                response.Clear();
                response.StatusCode = 404;
                response.Status     = "File " + Cid + " not found";
            }
            else
            {
                response.ContentType = entry.ContentType;
                response.AddHeader("content-disposition", String.Format("attachment; filename=\"{0}\"", GetFileName(entry)));

                response.OutputStream.Write(entry.Body, 0, entry.Body.Length);
                response.OutputStream.Flush();
            }

            response.End();
        }
Exemple #8
0
        /// <summary>
        /// Stores message to specified mailbox.
        /// </summary>
        /// <param name="mailbox">Mailbox name.</param>
        /// <param name="folder">Folder where to store message. Eg. 'Inbox'.</param>
        /// <param name="msgStream">Stream where message has stored.</param>
        /// <param name="to">Recipient email address.</param>
        /// <param name="from">Sendred email address.</param>
        /// <param name="isRelay">Specifies if message must be relayed.</param>
        /// <param name="date">Recieve date.</param>
        /// <param name="flags">Message flags.</param>
        public void StoreMessage(string p_mailfrom, string p_mailto, string p_folder, MemoryStream p_message)
        {
            //byte[] _topLines = null;
            //_topLines = GetTopLines(p_message, 50);

            try
            {
                var    _today  = DateTime.Now;
                string _fileid = Guid.NewGuid().ToString();

                string _mailbox = p_mailto;
                {
                    if (p_mailto.IndexOf("@") != -1)
                    {
                        _mailbox = p_mailto.Substring(0, p_mailto.IndexOf("@"));
                    }

                    var _sqlstr
                        = "INSERT INTO TB_eTAX_MAILBOX "
                          + "( "
                          + " fileid, mailbox, folder, data, size, sender, createtime "
                          + ") "
                          + "VALUES "
                          + "( "
                          + " @fileid, @mailbox, @folder, @data, @size, @sender, @createtime "
                          + ")";

                    var _dbps = new PgDatParameters();
                    {
                        _dbps.Add("@fileid", NpgsqlDbType.Varchar, _fileid);
                        _dbps.Add("@mailbox", NpgsqlDbType.Varchar, _mailbox);
                        _dbps.Add("@folder", NpgsqlDbType.Varchar, p_folder);
                        _dbps.Add("@data", NpgsqlDbType.Bytea, p_message.ToArray());
                        _dbps.Add("@size", NpgsqlDbType.Numeric, p_message.Length);
                        _dbps.Add("@sender", NpgsqlDbType.Varchar, p_mailfrom);
                        _dbps.Add("@createtime", NpgsqlDbType.TimestampTZ, _today);
                    }

                    if (LSQLHelper.ExecuteText(ConnectionString, _sqlstr, _dbps) < 1)
                    {
                        if (LogCommands == true)
                        {
                            ELogger.SNG.WriteLog(String.Format("mail insert failure: fileid: {0}, mailbox: {1}, folder: {2}, sender: {3}", _fileid, _mailbox, p_folder, p_mailfrom));
                        }
                    }
                    else
                    {
                        if (LogCommands == true && LiveServer == true)
                        {
                            ELogger.SNG.WriteLog(String.Format("mail insert success: fileid: {0}, mailbox: {1}, folder: {2}, sender: {3}", _fileid, _mailbox, p_folder, p_mailfrom));
                        }
                    }
                }

                if (MailSniffing == true)
                {
                    p_message.Seek(0, SeekOrigin.Begin);

                    string _directory = Path.Combine(USvcHelper.eMailFolder, IProvider.Proxy.ProductId);
                    {
                        _directory = Path.Combine(_directory, _mailbox);
                        _directory = Path.Combine(_directory, p_folder);
                        _directory = Path.Combine(_directory, _today.ToString("yyyyMMdd"));
                    }

                    string _filename = _fileid + ".eml";
                    QFWriter.QueueWrite(_directory, _filename, p_message.ToArray());
                }

                if (_mailbox == AspMailAddress)
                {
                    p_message.Seek(0, SeekOrigin.Begin);

                    MimeParser _parser = new MimeParser(p_message.ToArray());
                    if (_parser.MimeEntries.Count > 1)
                    {
                        MimeEntry _attachment = (MimeEntry)_parser.MimeEntries[1];
                        {
                            byte[] _obuffer = CmsManager.SNG.GetDecryptedContent(UCertHelper.AspKmCert.X509Cert2, _attachment.Data);

                            XmlDocument _taxdoc = new XmlDocument();
                            _taxdoc.LoadXml(Encoding.UTF8.GetString(_obuffer));

                            Reader  _reader      = new Reader(_taxdoc);
                            DataSet _purchaseSet = _reader.TaxPurchase();

                            LDltaHelper.InsertDeltaSet(ConnectionString, _purchaseSet);
                        }

                        // update [issueid] for compare with purchase-table.
                        string _issueid = Path.GetFileNameWithoutExtension(_attachment.FileName);
                        {
                            var _sqlstr
                                = "UPDATE TB_eTAX_MAILBOX "
                                  + "   SET filler0=@issueid "
                                  + " WHERE fileid=@fileid";

                            var _dbps = new PgDatParameters();
                            {
                                _dbps.Add("@fileid", NpgsqlDbType.Varchar, _fileid);
                                _dbps.Add("@issueid", NpgsqlDbType.Varchar, _issueid);
                            }

                            if (LSQLHelper.ExecuteText(ConnectionString, _sqlstr, _dbps) < 1)
                            {
                                if (LogCommands == true)
                                {
                                    ELogger.SNG.WriteLog(String.Format("mail update failure: fileid: {0}, issueid: {1}, sender: {2}", _fileid, _issueid, p_mailfrom));
                                }
                            }
                            else
                            {
                                if (LogCommands == true && LiveServer == true)
                                {
                                    ELogger.SNG.WriteLog(String.Format("mail update success: fileid: {0}, issueid: {1}, sender: {2}", _fileid, _issueid, p_mailfrom));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ELogger.SNG.WriteLog(ex);
            }
        }
Exemple #9
0
        private static string ConstructNonMultiPart(MimeEntry ent, bool bodystructure)
        {
            string str = "(";

            // contentType
            str += "\"" + ent.ContentType.Split('/')[0] + "\" ";

            // conentSubType
            if (ent.ContentType.Split('/').Length == 2)
            {
                str += "\"" + ent.ContentType.Split('/')[1].Replace(";", "") + "\" ";
            }
            else
            {
                str += "NIL ";
            }

            // conentTypeSubFields
            string longContentType = MimeParser.ParseHeaderField("Content-Type:", ent.Headers);

            if (longContentType.IndexOf(";") > -1)
            {
                str += "(";
                string[] fields = longContentType.Split(';');
                for (int i = 1; i < fields.Length; i++)
                {
                    string[] nameValue = fields[i].Replace("\"", "").Trim().Split(new char[] { '=' }, 2);

                    str += "\"" + nameValue[0] + "\" \"" + nameValue[1] + "\"";

                    if (i < fields.Length - 1)
                    {
                        str += " ";
                    }
                }
                str += ") ";
            }
            else
            {
                // if content is attachment and content type name filed is missing, use filename for it
                string fileName = MimeParser.ParseHeaderFiledSubField("Content-Disposition:", "filename", ent.Headers);
                if (fileName.Length > 0)
                {
                    str += "(\"name\" \"" + fileName + "\") ";
                }
                else
                {
                    str += "NIL ";
                }
            }

            // contentID
            string contentID = MimeParser.ParseHeaderField("Content-ID:", ent.Headers);

            if (contentID.Length > 0)
            {
                str += "\"" + contentID + "\" ";
            }
            else
            {
                str += "NIL ";
            }

            // contentDescription
            string contentDescription = MimeParser.ParseHeaderField("Content-Description:", ent.Headers);

            if (contentDescription.Length > 0)
            {
                str += "\"" + contentDescription + "\" ";
            }
            else
            {
                str += "NIL ";
            }

            // contentEncoding
            str += "\"" + ent.ContentEncoding + "\" ";

            // contentSize
            str += ent.DataNonDecoded.Length + " ";

            // envelope NOTE: included only if contentType = "message" !!!

            // contentLines NOTE: included only if contentType = "text" !!!
            if (ent.ContentType.ToLower().IndexOf("text") > -1)
            {
                StreamLineReader r = new StreamLineReader(new MemoryStream(ent.DataNonDecoded));
                int    nLines      = 0;
                byte[] line        = new byte[0];
                while (line != null)
                {
                    line = r.ReadLine();
                    nLines++;
                }
                str += nLines;
            }

            // Need to add extended fields
            if (bodystructure)
            {
                str += " ";

                // md5
                str += "NIL ";

                // contentDisposition
                string contDispos = MimeParser.ParseHeaderField("Content-Disposition:", ent.Headers);
                if (contDispos.Length > 0)
                {
                    str += "(";

                    string[] fields = contDispos.Split(';');

                    str += "\"" + fields[0] + "\" ";

                    if (fields.Length > 1)
                    {
                        str += "(";
                        for (int i = 1; i < fields.Length; i++)
                        {
                            string[] nameValue = fields[i].Replace("\"", "").Trim().Split(new char[] { '=' }, 2);

                            str += "\"" + nameValue[0] + "\" \"" + nameValue[1] + "\"";

                            if (i < fields.Length - 1)
                            {
                                str += " ";
                            }
                        }
                        str += ")";
                    }
                    else
                    {
                        str += "NIL";
                    }

                    str += ") ";
                }
                else
                {
                    str += "NIL ";
                }

                // contentLanguage
                str += "NIL";
            }

            str += ")";

            return(str);
        }
Exemple #10
0
        /// <summary>
        /// Create a new item in a folder based on a input MIME stream entered by user
        /// </summary>
        /// <param name="sender">The parameter is not used.</param>
        /// <param name="e">The parameter is not used.</param>
        private void MnuCreateFromMimeEntry_Click(object sender, EventArgs e)
        {
            //OpenFileDialog ofd = new OpenFileDialog();
            //ofd.Title = "Choose a MIME file to import...";
            //ofd.Multiselect = false;
            this.Cursor = Cursors.WaitCursor;

            bool bItemCreated = false;

            // Defeat warnings on bItemSaved - end
            bool bjunk = false;

            bItemCreated = bjunk;
            bjunk        = bItemCreated;
            // Defeat warnings on bItemSaved - end

            bool bSupportedFolderType = false;

            string sFolderClass = this.currentFolder.FolderClass;

            if (sFolderClass.StartsWith("IPF.Appointment") ||
                sFolderClass.StartsWith("IPF.Contact") ||
                sFolderClass.StartsWith("IPF.Note")
                )
            {
                bSupportedFolderType = true;
                MimeEntry oMimeEntry = new MimeEntry(this.CurrentService, this.currentFolder);
                oMimeEntry.ShowDialog();

                if (oMimeEntry.ItemCreated == true)
                {
                    this.RefreshContentAndDetails();
                }
            }

            //if (this.currentFolder.FolderClass.StartsWith("IPF.Appointment"))
            //{
            //    bSupportedFolderType = true;
            //    Appointment item = new Appointment(this.CurrentService);
            //    item.MimeContent = new MimeContent();

            //    MimeEntry oMimeEntry = new MimeEntry();
            //    oMimeEntry.ShowDialog();
            //    string sContent = string.Empty;

            //    if (oMimeEntry.ChoseOK == true)
            //    {
            //        if (oMimeEntry.chkIsBase64Encoded.Checked == true)
            //            item.MimeContent.Content = Convert.FromBase64String(oMimeEntry.txtEntry.Text.Trim());
            //        else
            //            item.MimeContent.Content = System.Text.Encoding.UTF8.GetBytes(oMimeEntry.txtEntry.Text);

            //        item.Save(this.currentFolder.Id);
            //        this.RefreshContentAndDetails();
            //    }

            //    bItemCreated = true;
            //    item = null;

            //}
            //if (this.currentFolder.FolderClass.StartsWith("IPF.Contact"))
            //{
            //    bSupportedFolderType = true;
            //    Contact item = new Contact(this.CurrentService);
            //    item.MimeContent = new MimeContent();

            //    MimeEntry oMimeEntry = new MimeEntry();
            //    oMimeEntry.ShowDialog();
            //    if (oMimeEntry.ChoseOK == true)
            //    {
            //        if (oMimeEntry.chkIsBase64Encoded.Checked == true)
            //            item.MimeContent.Content = Convert.FromBase64String(oMimeEntry.txtEntry.Text.Trim());
            //        else
            //            item.MimeContent.Content = System.Text.Encoding.UTF8.GetBytes(oMimeEntry.txtEntry.Text);

            //        item.Save(this.currentFolder.Id);
            //        this.RefreshContentAndDetails();

            //    }

            //    bItemCreated = true;
            //    item = null;
            //}
            //if (this.currentFolder.FolderClass.StartsWith("IPF.Note"))
            //{
            //    bSupportedFolderType = true;
            //    EmailMessage item = new EmailMessage(this.CurrentService);
            //    item.MimeContent = new MimeContent();

            //    MimeEntry oMimeEntry = new MimeEntry();

            //    oMimeEntry.ShowDialog();
            //    if (oMimeEntry.ChoseOK == true)
            //    {
            //        if (oMimeEntry.chkIsBase64Encoded.Checked == true)
            //            item.MimeContent.Content = Convert.FromBase64String(oMimeEntry.txtEntry.Text.Trim());
            //        else
            //            item.MimeContent.Content = System.Text.Encoding.UTF8.GetBytes(oMimeEntry.txtEntry.Text);

            //        item.Save(this.currentFolder.Id);
            //        this.RefreshContentAndDetails();

            //    }

            //    bItemCreated = true;
            //    item = null;

            //}

            // Tasks are not standarding messaging items and there is no MIME for them. EWS can generate a MIME type
            // string for a Task but not create an item using MIME. Tasks are Outlook items.

            if (bSupportedFolderType == false)
            {
                if (this.currentFolder.FolderClass.StartsWith("IPF.Note"))  // Task specific error...
                {
                    string s =
                        "Tasks are not standarding messaging items and there is no MIME for them. " +
                        "EWS can generate a MIME type string for a Task but not create an item using MIME. " +
                        "Tasks are Outlook items.";

                    MessageBox.Show(s, "MIME loading for Tasks type items not implemented.");
                }
                else
                {
                    string s2 =
                        "MIME loading for this folder type not implemented. " +
                        "Note that not all items have a MIME type. " +
                        "Some items such as Tasks are Outlook items and not standard messaging items which have a MIME form.";
                    MessageBox.Show(s2, "MIME loading for this folder type not implemented.");
                }
            }

            this.Cursor = Cursors.Default;
        }