コード例 #1
0
ファイル: MailboxService.cs プロジェクト: seif/papercut-web
        private static MailMessageEx GetMailMessage(string file)
        {
            var allLines   = File.ReadAllLines(file);
            var mimeReader = new MimeReader(allLines);

            return(mimeReader.CreateMimeEntity().ToMailMessageEx());
        }
コード例 #2
0
        /// <summary> Возвращает список id для всех сообщений в почтовом ящике удовлетворяющих критерию поиска </summary>
        /// <returns> criteria => "from=*s.belo* subject=FW:*"</returns>
        /// <remarks> Сообщения, помеченные для удаления, не перечисляются.</remarks>
        public List <int> GetMessageList(string criteria, Encoding encoding = null)
        {
            var result  = new List <int>();
            var filters = ParseCriteria(criteria);

            var oldEncoding = Encoding;

            Encoding = encoding ?? Encoding;
            try
            {
                foreach (var v in GetMessageList())
                {
                    var m = new MimeReader(GetResponse("TOP {0} 0".FormatStr(v), true).Data);
                    foreach (var f in filters)
                    {
                        if (!MimeReader.DecodeWord(m.Headers[f.Key] + "").Trim().IsMatch(f.Value))
                        {
                            m = null; break;
                        }
                    }
                    if (m != null)
                    {
                        result.Add(v);
                    }
                }
            }
            finally
            {
                Encoding = oldEncoding;
            }
            return(result);
        }
コード例 #3
0
 internal void SetContentType(ContentType contentType)
 {
     this._contentType           = contentType;
     this._contentType.MediaType = MimeReader.GetMediaType(contentType.MediaType);
     this._mediaMainType         = MimeReader.GetMediaMainType(contentType.MediaType);
     this._mediaSubType          = MimeReader.GetMediaSubType(contentType.MediaType);
 }
コード例 #4
0
 private void BuildMultiPartMessage(MimeReader reader)
 {
     foreach (MimeReader child in reader.Children)
     {
         if (child.ContentType.MediaType.StartsWith("multipart", StringComparison.Ordinal))
         {
             BuildMultiPartMessage(child);
         }
         else if (child.ContentType.MediaType == MediaTypeNames.Text.Html)
         {
             AddAlternateView(child); //multipart/alternative; - parent
         }
         else if (child.ContentType.MediaType == MediaTypeNames.Text.Plain && child.ContentDisposition == null)
         {
             BuildSinglePartMessage(child);
         }
         else if (child.ContentType.MediaType == "message/rfc822") //что делать с другими сообщениями типа message/*
         {
             Children.Add(new MailMimeMessage(child, DefaultEncoding));
         }
         else if (child.ContentDisposition != null && !child.ContentDisposition.Inline)
         {
             AddAttachment(child);
         }
     }
 }
コード例 #5
0
ファイル: Pop3Client.cs プロジェクト: yusws/Codeplex
        public MailMessageEx Top(int messageId, int lineCount)
        {
            if (messageId < 1)
            {
                throw new ArgumentOutOfRangeException("messageId");
            }

            if (lineCount < 0)
            {
                throw new ArgumentOutOfRangeException("lineCount");
            }

            RetrResponse response;

            using (TopCommand command = new TopCommand(_clientStream, messageId, lineCount))
            {
                response = ExecuteCommand <RetrResponse, TopCommand>(command);
            }

            MimeReader    reader  = new MimeReader(response.MessageLines);
            MimeEntity    entity  = reader.CreateMimeEntity();
            MailMessageEx message = entity.ToMailMessageEx();

            message.Octets        = response.Octets;
            message.MessageNumber = messageId;
            return(entity.ToMailMessageEx());
        }
コード例 #6
0
        public static async Task TwoChildrenTest()
        {
            var        stream    = typeof(MimeTests).GetResource("testdata.two-children.eml");
            MimeReader reader    = new MimeReader();
            var        structure = await reader.ReadStructureAsync(stream, CancellationToken.None);

            await TestContent(structure,
                              stream,
                              new ExpectedPart(
                                  new Dictionary <string, string>
            {
                { "From", " From Name <*****@*****.**>" },
                { "To", " To Name<*****@*****.**>" },
                { "Subject", " Sample message" },
                { "MIME-Version", " 1.0" },
                { "Content-Type", " multipart/mixed; boundary=\"simple boundary\"" },
            },
                                  "This is the preamble.  It is to be ignored, though it\r\nis a handy place for mail composers to include an\r\nexplanatory note to non-MIME compliant readers.",
                                  "This is the epilogue.  It is also to be ignored.\r\n",
                                  new ExpectedPart(
                                      new Dictionary <string, string>(),
                                      "This is implicitly typed plain ASCII text.\r\nIt does NOT end with a linebreak."),
                                  new ExpectedPart(
                                      new Dictionary <string, string>
            {
                { "Content-type", " text/plain; charset=us-ascii" },
            },
                                      "This is explicitly typed plain ASCII text.\r\nIt DOES end with a linebreak.\r\n"))
                              );
        }
コード例 #7
0
        public ActionResult Mail()
        {
            MimeReader mime = new MimeReader();

            var vm   = new List <MailViewModel>();
            var path = HostingEnvironment.MapPath(@"/App_Data");

            foreach (var file in Directory.GetFiles($@"{path}", "*.eml"))
            {
                RxMailMessage msg = mime.GetEmail(file);


                vm.Add(new MailViewModel()
                {
                    Id   = Path.GetFileNameWithoutExtension(file),
                    Sent = msg.DeliveryDate,
                    To   = msg.To.Select(s => s.Address.ToString()),
                    CC   = msg.CC.Select(s => s.Address.ToString()),

                    From        = msg.From.Address,
                    Subject     = msg.Subject.Replace("(Trial Version)", ""),
                    Body        = msg.Body,
                    Attachments = msg.Attachments.ToList()
                });
            }

            return(View(vm.OrderByDescending(x => x.Sent)));
        }
コード例 #8
0
 public MimeEntity()
 {
     this._children       = new List <MimeEntity>();
     this._headers        = new NameValueCollection();
     this._contentType    = MimeReader.GetContentType(string.Empty);
     this._parent         = null;
     this._encodedMessage = new StringBuilder();
 }
コード例 #9
0
 // Token: 0x06000229 RID: 553 RVA: 0x00009876 File Offset: 0x00007A76
 public static HeaderList ReadFrom(MimeReader reader)
 {
     if (reader == null)
     {
         throw new ArgumentNullException("reader");
     }
     return(reader.ReadHeaderList());
 }
コード例 #10
0
        private void BuildSinglePartMessage(MimeReader reader)//может сделать уже в итоге на основе AlternateViews???
        {
            Encoding encoding = MimeReader.GetEncoding(reader.ContentType.CharSet);

            Body         = encoding.GetString(reader.GetContent());
            BodyEncoding = encoding;
            IsBodyHtml   = string.Equals(MediaTypeNames.Text.Html, reader.ContentType.MediaType, StringComparison.InvariantCultureIgnoreCase);
        }
コード例 #11
0
 public async Task <IActionResult> PostLibrary([FromRoute] long idCompany, [FromRoute] long idWeek,
                                               [FromForm(Name = "file")] IFormFile formFile)
 {
     try
     {
         if (formFile != null)
         {
             var directory = Directory.GetCurrentDirectory() + "/storage/wer/";
             if (!Directory.Exists(directory))
             {
                 Directory.CreateDirectory(directory);
             }
             var filePath = directory + Guid.NewGuid() + Path.GetExtension(formFile.FileName);
             if (formFile.Length > 0)
             {
                 using (var stream = new FileStream(filePath, FileMode.Create))
                 {
                     await formFile.CopyToAsync(stream);
                 }
             }
             var file = _filesRepository.createFile(new FileCompanyEntity()
             {
                 Mime      = MimeReader.GetMimeType(Path.GetExtension(formFile.FileName)),
                 Name      = formFile.FileName,
                 Uri       = filePath,
                 Extension = Path.GetExtension(formFile.FileName),
                 WeekId    = idWeek,
                 CompanyId = idCompany,
                 UserId    = HttpContext.UserId().Value
             });
             if (file != null)
             {
                 return(new ObjectResult(file)
                 {
                     StatusCode = 201
                 });
             }
             else
             {
                 System.IO.File.Delete(filePath);
                 return(StatusCode(500));
             }
         }
         else
         {
             return(new BadRequestResult());
         }
     }
     catch (Exception exception)
     {
         Console.WriteLine(exception);
         return(StatusCode(500)); // 500 is generic server error
     }
 }
コード例 #12
0
        public static async Task Nested()
        {
            var        stream    = typeof(MimeTests).GetResource("testdata.nested.eml");
            MimeReader reader    = new MimeReader();
            var        structure = await reader.ReadStructureAsync(stream, CancellationToken.None);

            await TestContent(structure,
                              stream,
                              new ExpectedPart(
                                  new Dictionary <string, string>
            {
                { "MIME-Version", " 1.0" }, { "From", " Nathaniel Borenstein <*****@*****.**>" },
                { "To", " Ned Freed <*****@*****.**>" }, { "Subject", " A multipart example" },
                { "Content-Type", " multipart/mixed;\r\n     boundary=unique-boundary-1" },
            },
                                  "This is the preamble area of a multipart message.\r\nMail readers that understand multipart format\r\nshould ignore this preamble.\r\nIf you are reading this text, you might want to\r\nconsider changing to a mail reader that understands\r\nhow to properly display multipart messages.",
                                  "",
                                  new ExpectedPart(
                                      new Dictionary <string, string>(),
                                      "\r\n...Some text appears here...\r\n\r\n\r\n[Note that the preceding blank line means\r\nno header fields were given and this is text,\r\nwith charset US ASCII.  It could have been\r\ndone with explicit typing as in the next part.]\r\n"),
                                  new ExpectedPart(new Dictionary <string, string>
            {
                { "Content-type", " text/plain; charset=US-ASCII" },
            },
                                                   "This could have been part of the previous part,\r\nbut illustrates explicit versus implicit\r\ntyping of body parts.\r\n"),
                                  new ExpectedPart(new Dictionary <string, string>
            {
                { "Content-Type", " multipart/parallel;\r\n     boundary=\"unique-\\\"boundary-2\\\"\"" },
            },
                                                   "",
                                                   "",
                                                   new ExpectedPart(new Dictionary <string, string>
            {
                { "Content-Type", " audio/basic" }, { "Content-Transfer-Encoding", " base64" },
            },
                                                                    "\r\n... base64-encoded 8000 Hz single-channel\r\n mu-law-format audio data goes here....\r\n"),
                                                   new ExpectedPart(new Dictionary <string, string>
            {
                { "Content-Type", " image/gif" }, { "Content-Transfer-Encoding", " base64" },
            },
                                                                    "\r\n... base64-encoded image data goes here....\r\n\r\n")
                                                   ),
                                  new ExpectedPart(new Dictionary <string, string>
            {
                { "Content-type", " text/richtext" },
            },
                                                   "This is <bold><italic>richtext.</italic></bold>\r\n<smaller>as defined in RFC 1341</smaller>\r\n<nl><nl>Isn\'t it\r\n<bigger><bigger>cool?</bigger></bigger>\r\n"),
                                  new ExpectedPart(new Dictionary <string, string> {
                { "Content-Type", " message/rfc822" },
            },
                                                   "From: (mailbox in US-ASCII)\r\nTo: (address in US-ASCII)\r\nSubject: (subject in US-ASCII)\r\nContent-Type: Text/plain; charset=ISO-8859-1\r\nContent-Transfer-Encoding: Quoted-printable\r\n\r\n\r\n... Additional text in ISO-8859-1 goes here ...\r\n\r\n")
                                  )
                              );
        }
コード例 #13
0
        public object Get()
        {
            MimeReader mime = new MimeReader();     // this class processes the .EML mime content

            // this get's the MailMessage into Peter's RxMailMessage class
            // which is derived from the MS MailMessage class
            string        sEmlPath = @"C:\Temp\emails\approve-task.eml";
            RxMailMessage mm       = mime.GetEmail(sEmlPath);
            var           dto      = _context.Users.Include(g => g.Groups).ToList();

            return(Ok(dto));
        }
コード例 #14
0
        public string GetBody(string path)
        {
            MimeReader mime = new MimeReader();

            RxMailMessage mm = mime.GetEmail(path);

            return(GetPlainText(mm));

            //divList.Style.Add("display", "none");

            //divDetails.Style.Remove("display");
        }
コード例 #15
0
        private MailMimeMessage AddAlternateView(MimeReader reader)
        {
            var alternateView = new AlternateView(new MemoryStream(reader.GetContent(), false), reader.ContentType);
            var te            = reader.GetTransferEncoding();

            if (te != TransferEncoding.Unknown)
            {
                alternateView.TransferEncoding = te;                                 //fix bug for Content-Type: text/html;
            }
            try { alternateView.ContentId = TrimBrackets(Headers["content-id"] + ""); }
            catch { } //refactor
            AlternateViews.Add(alternateView);
            return(this);
        }
コード例 #16
0
 private void AssertGood(bool checkPositionedOnHeader)
 {
     if (this.reader == null)
     {
         throw new NotSupportedException(Strings.HeaderReaderNotInitialized);
     }
     this.reader.AssertGoodToUse(true, true);
     if (!MimeReader.StateIsOneOf(this.reader.ReaderState, MimeReaderState.PartStart | MimeReaderState.HeaderStart | MimeReaderState.HeaderIncomplete | MimeReaderState.HeaderComplete | MimeReaderState.EndOfHeaders | MimeReaderState.InlineStart))
     {
         throw new NotSupportedException(Strings.HeaderReaderCannotBeUsedInThisState);
     }
     if (checkPositionedOnHeader && MimeReader.StateIsOneOf(this.reader.ReaderState, MimeReaderState.PartStart | MimeReaderState.EndOfHeaders))
     {
         throw new InvalidOperationException(Strings.HeaderReaderIsNotPositionedOnAHeader);
     }
 }
コード例 #17
0
        private ExDateTime GetReceivedDate(Stream mimeStream, bool useSentTime)
        {
            ExDateTime?exDateTime = null;

            try
            {
                using (MimeReader mimeReader = new MimeReader(new SuppressCloseStream(mimeStream)))
                {
                    if (mimeReader.ReadNextPart())
                    {
                        while (mimeReader.HeaderReader.ReadNextHeader())
                        {
                            if (mimeReader.HeaderReader.HeaderId == HeaderId.Received)
                            {
                                ReceivedHeader receivedHeader = Header.ReadFrom(mimeReader.HeaderReader) as ReceivedHeader;
                                if (receivedHeader != null && receivedHeader.Date != null)
                                {
                                    DateTime dateTime = this.ToDateTime(receivedHeader.Date);
                                    return(new ExDateTime(ExTimeZone.UtcTimeZone, dateTime));
                                }
                            }
                            if (useSentTime && mimeReader.HeaderReader.HeaderId == HeaderId.Date)
                            {
                                DateHeader dateHeader = Header.ReadFrom(mimeReader.HeaderReader) as DateHeader;
                                if (dateHeader != null)
                                {
                                    exDateTime = new ExDateTime?(new ExDateTime(ExTimeZone.UtcTimeZone, dateHeader.DateTime));
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                mimeStream.Seek(0L, SeekOrigin.Begin);
            }
            if (exDateTime != null)
            {
                return(exDateTime.Value);
            }
            return(ExDateTime.MinValue);
        }
コード例 #18
0
        private MailMimeMessage AddAttachment(MimeReader reader)
        {
            //возможы FormatException для смещения времени по UTC на 0, должно быть исправленно в FW4
            var attachment = new Attachment(new MemoryStream(reader.GetContent(), false), reader.ContentType);
            var te         = reader.GetTransferEncoding();

            if (te != TransferEncoding.Unknown)
            {
                attachment.TransferEncoding = te;                                 //важно установить до установки attachment.ContentDisposition.FileName (а то возможен FormatException )
            }
            if (reader.ContentDisposition != null)
            {
                var cd = reader.ContentDisposition;
                foreach (string key in cd.Parameters.Keys)
                {
                    switch (key)
                    {
                    //PATCH: обход глюка в .NET 4 - происходит падение при следующем сценарии:
                    //var cd = new ContentDisposition();
                    //cd.Parameters.Add("creation-date", "Thu, 09 Oct 2014 09:56:31 +0400");
                    //var cd2 = new ContentDisposition();
                    //cd2.Parameters.Add("creation-date", cd.Parameters["creation-date"]);

                    case "creation-date": attachment.ContentDisposition.CreationDate = cd.CreationDate; break;

                    case "modification-date": attachment.ContentDisposition.ModificationDate = cd.ModificationDate; break;

                    case "read-date": attachment.ContentDisposition.ReadDate = cd.ReadDate; break;

                    default: attachment.ContentDisposition.Parameters.Add(key, cd.Parameters[key]); break;
                    }
                }
            }

            if (!reader.Headers["content-id"].IsEmpty())
            {
                try { attachment.ContentId = TrimBrackets(Headers["content-id"]); }
                catch { } //refactor
            }
            Attachments.Add(attachment);
            return(this);
        }
コード例 #19
0
        private static void DATA(Connection connection)
        {
            // Check command order
            if (connection.Session.Sender == null || connection.Session.MailFrom == null || connection.Session.Recipients.Count == 0)
            {
                connection.Send("503 Bad sequence of commands");
                return;
            }

            string file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("yyyyMMddHHmmssFF") + ".eml");

            try
            {
                var lines = new StringBuilder();

                using (var networkStream = new NetworkStream(connection.Client, false))
                    using (var reader = new StreamReader(networkStream))
                    {
                        connection.Send("354 Start mail input; end with <CRLF>.<CRLF>").AsyncWaitHandle.WaitOne();
                        string line;

                        while ((line = reader.ReadLine()) != ".")
                        {
                            lines.AppendLine(line);
                        }
                    }

                var mimeReader = new MimeReader(lines.ToString().Replace("\r\n", "\n").Split('\n'));
                var entity     = mimeReader.CreateMimeEntity();
                var message    = entity.ToMailMessageEx();
                OnMessageReceived(connection, message);
            }
            catch (IOException e)
            {
                Logger.WriteWarning("IOException received in Processor.DATA while reading message.  Closing connection.  Message: " + e.Message, connection.ConnectionId);
                connection.Close();
                return;
            }

            connection.Send("250 OK");
        }
コード例 #20
0
        public void WritePart(MimeReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }
            this.AssertOpen();
            if (!MimeReader.StateIsOneOf(reader.ReaderState, MimeReaderState.PartStart | MimeReaderState.InlineStart))
            {
                throw new InvalidOperationException(Strings.OperationNotValidInThisReaderState);
            }
            this.StartPart();
            MimeHeaderReader headerReader = reader.HeaderReader;

            while (headerReader.ReadNextHeader())
            {
                this.WriteHeader(headerReader);
            }
            this.WriteContent(reader);
            this.EndPart();
        }
コード例 #21
0
        /// <summary>
        /// Retrs the specified message.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns>A MimeEntity for the requested Pop3 Mail Item.</returns>
        public MimeEntity RetrMimeEntity(Pop3ListItem item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (item.MessageId < 1)
            {
                throw new ArgumentOutOfRangeException("item.MessageId");
            }

            RetrResponse response;
            using (RetrCommand command = new RetrCommand(_clientStream, item.MessageId))
            {
                response = ExecuteCommand<RetrResponse, RetrCommand>(command);
            }

            MimeReader reader = new MimeReader(response.MessageLines);
            return reader.CreateMimeEntity();
        }
コード例 #22
0
 public void WriteContent(MimeReader reader)
 {
     if (reader == null)
     {
         throw new ArgumentNullException("reader");
     }
     this.AssertOpen();
     if (this.contentWritten)
     {
         throw new InvalidOperationException(Strings.ContentAlreadyWritten);
     }
     using (Stream rawContentReadStream = reader.GetRawContentReadStream())
     {
         if (rawContentReadStream != null)
         {
             using (Stream rawContentWriteStream = this.GetRawContentWriteStream())
             {
                 DataStorage.CopyStreamToStream(rawContentReadStream, rawContentWriteStream, long.MaxValue, ref this.scratchBuffer);
             }
         }
     }
 }
コード例 #23
0
        public static async Task SimpleMimeTest()
        {
            var        stream    = typeof(MimeTests).GetResource("testdata.simple.eml");
            MimeReader reader    = new MimeReader();
            var        structure = await reader.ReadStructureAsync(stream, CancellationToken.None);

            await TestContent(structure,
                              stream,
                              new ExpectedPart(
                                  new Dictionary <string, string>
            {
                { "Return-Path", " <*****@*****.**>" },
                { "From", " \"Sender Name\" <*****@*****.**>" },
                { "To", " \"Recipient Name\" <*****@*****.**>,\r\n\t\"Other Name\" <*****@*****.**>" },
                { "Subject", " Sample subject" },
                { "MIME-Version", " 1.0" },
                { "Content-Type", " text/plain;\r\n\tcharset=\"us-ascii\"" },
                { "Content-Transfer-Encoding", " 7bit" },
            },
                                  "Test body\r\n\r\nTest paragraph\r\n"
                                  )
                              );
        }
コード例 #24
0
 private static void readMail()
 {
     try
     {
         foreach (string file in Directory.EnumerateFiles(ConfigurationManager.AppSettings["sEmlPath"]))
         {
             if (file.Contains(".msg"))
             {
                 ReadMsgFile.ReadOutlookMail(file);
             }
             else
             {
                 MimeReader    mime   = new MimeReader();
                 RxMailMessage mm     = mime.GetEmail(file);
                 string        detils = ReadEmlFile.GetPlainText(mm);
             }
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
コード例 #25
0
        private void LeerEML(string Carpeta, string Archivo, string PST, Int16 IdPST)
        {
            try
            {
                MimeReader mime      = new MimeReader();
                string     Remitente = "";
                Int64      IdCorreo  = 0;
                //FechaIniPerf = DateTime.Now; //TrackPerformance
                RxMailMessage msg = mime.GetEmail(Archivo);
                //RegistrarLogDesempenno("GetEmail"); //TrackPerformance

                if (msg != null)
                {
                    List <stAdjuntos> Adjuntos           = new List <stAdjuntos> {
                    };
                    List <stDestinatarios> Destinatarios = new List <stDestinatarios> {
                    };

                    //FechaIniPerf = DateTime.Now; //TrackPerformance
                    Adjuntos = ObtenerAdjuntos(Carpeta, Archivo, PST);
                    //RegistrarLogDesempenno("ObtenerAdjuntos"); //TrackPerformance
                    //FechaIniPerf = DateTime.Now; //TrackPerformance
                    Destinatarios = ObtenerDestinarios(ref msg, PST, Archivo);
                    //RegistrarLogDesempenno("ObtenerDestinarios"); //TrackPerformance

                    if (msg.From != null)
                    {
                        Remitente = msg.From.Address;
                    }
                    else
                    {
                        if (msg.Sender != null)
                        {
                            Remitente = msg.Sender.Address;
                        }
                        else
                        {
                            Remitente = "";
                        }
                    }

                    //FechaIniPerf = DateTime.Now; //TrackPerformance
                    IdCorreo = InsertarCorreo(IdPST, Remitente, msg.DeliveryDate, msg.Subject, GetMailText(msg), Archivo, PST, Carpeta.Replace(vRuta, ""));
                    //RegistrarLogDesempenno("InsertarCorreo"); //TrackPerformance

                    if (IdCorreo > 0)
                    {
                        foreach (stAdjuntos att in Adjuntos.Distinct())
                        {
                            try
                            {
                                //FechaIniPerf = DateTime.Now; //TrackPerformance
                                InsertarAdjuntos(IdCorreo, Carpeta.Replace(vRuta, ""), att.Archivo, att.Extension, att.Tamanno);
                                //RegistrarLogDesempenno("InsertarAdjuntos"); //TrackPerformance
                            }
                            catch (Exception ex)
                            {
                                RegistrarLogLocal("InsertarAdjuntosCall", ex.Message, PST, Archivo);
                            }
                        }

                        List <string> DestinatariosF = new List <string> {
                        };

                        foreach (stDestinatarios dest in Destinatarios.Distinct())
                        {
                            try
                            {
                                //FechaIniPerf = DateTime.Now; //TrackPerformance
                                if (!DestinatariosF.Contains(dest.Direccion))
                                {
                                    InsertarDestinatarios(IdCorreo, dest.Direccion, dest.Nombre);
                                    DestinatariosF.Add(dest.Direccion);
                                }
                                //RegistrarLogDesempenno("InsertarDestinatarios"); //TrackPerformance
                            }
                            catch (Exception ex)
                            {
                                RegistrarLogLocal("InsertarDestinatariosCall", ex.Message, PST, Archivo);
                            }
                        }
                    }

                    msg.Dispose();
                }
            }
            catch (Exception ex)
            {
                RegistrarLogLocal("LeerEML", ex.Message, PST, Archivo);
            }
        }
コード例 #26
0
        public MailMimeMessage(MimeReader reader, Encoding defaultEncoding)
        {
            if (defaultEncoding != null)
            {
                DefaultEncoding = defaultEncoding;
            }
            if (!reader.ContentType.Boundary.IsEmpty())
            {
                BuildMultiPartMessage(reader);
            }
            else if (reader.ContentType.MediaType == "message/rfc822")
            {
                if (reader.Children.Count == 0)
                {
                    throw new Exception("Invalid child count on message/rfc822 entity.");
                }
                BuildMultiPartMessage(reader.Children[0]);                                                           //заголовок внутри сообщения
            }
            else if (reader.ContentDisposition != null && reader.ContentDisposition.DispositionType == "attachment") //fix dong bug
            {
                AddAttachment(reader);
            }
            else
            {
                BuildSinglePartMessage(reader);
            }

            string value = "";

            foreach (string key in reader.Headers.AllKeys)
            {
                value = reader.Headers[key].IfEmpty(" ");
                try
                {
                    Headers.Add(key, value);
                }
                catch (FormatException)                                                                                                             //value not ASCII (т.е. не Subject: =?koi8-r?B?79TQ1dPLwQ==?=)
                {
                    Headers.Add(key, @"=?{0}?B?{1}?=".FormatStr(DefaultEncoding.WebName, Convert.ToBase64String(DefaultEncoding.GetBytes(value)))); //некоторые присылают не ascii (c FW4 - поддерживается UTF-8 )
                }

                value = MimeReader.DecodeWord(value);
                switch (key)
                {
                case "bcc":
                    if (!IsUndisclosed(value))
                    {
                        Array.ForEach(SplitAddresses(value), Bcc.Add);
                    }
                    break;

                case "cc":
                    if (!IsUndisclosed(value))
                    {
                        Array.ForEach(SplitAddresses(value), CC.Add);
                    }
                    break;

                case "from":
                    if (!IsUndisclosed(value))
                    {
                        From = CreateMailAddress(value);
                    }
                    break;

                case "reply-to":
                    if (!IsUndisclosed(value))
                    {
                        Array.ForEach(SplitAddresses(value), ReplyToList.Add);
                    }
                    //ReplyTo = CreateMailAddress(value);
                    break;

                case "subject":
                    Subject         = value.ReplaceAny("", Environment.NewLine);
                    SubjectEncoding = Encoding.UTF8;
                    break;

                case "to":
                    if (!IsUndisclosed(value))
                    {
                        Array.ForEach(SplitAddresses(value), To.Add);
                    }
                    break;
                }
            }
        }
コード例 #27
0
 internal MimeHeaderReader(MimeReader reader)
 {
     this.reader = reader;
 }
コード例 #28
0
 internal MimeParameterReader(MimeReader reader)
 {
     this.reader = reader;
 }
コード例 #29
0
        /// <summary>
        /// Reads the MIME parameters
        /// </summary>
        private void ReadMimeMessage()
        {
            string boundary = ContentType.Split(new string[] { "boundary=" }, StringSplitOptions.RemoveEmptyEntries)[1];

            _MimeReader = new MimeReader(boundary, Content.AsStream());
        }
コード例 #30
0
 private void ProcessResponse()
 {
     string responseContentType = this.RequestExecutor.ResponseContentType;
     HttpStatusCode statusCode = this.RequestExecutor.StatusCode;
     string boundary;
     bool flag = this.IsMultiPartMime(responseContentType, out boundary);
     if (statusCode != HttpStatusCode.OK || (!responseContentType.StartsWith("application/json") && !flag))
     {
         this.m_requestStatus = ClientRequestStatus.CompletedException;
         throw new ClientRequestException(Resources.GetString("RequestUnexpectedResponseWithContentTypeAndStatus", new object[]
         {
             responseContentType,
             statusCode
         }));
     }
     this.m_context.ProcessingResponse = true;
     try
     {
         using (Stream responseStream = this.RequestExecutor.GetResponseStream())
         {
             MimeReader mimeReader = null;
             Stream responseStream2 = responseStream;
             if (flag)
             {
                 mimeReader = new MimeReader(responseStream, boundary);
                 if (!mimeReader.ReadNextPart())
                 {
                     throw new ClientRequestException(Resources.GetString("RequestUnexpectedResponseWithContentTypeAndStatus", new object[]
                     {
                         responseContentType,
                         statusCode
                     }));
                 }
                 responseStream2 = mimeReader.GetContentStream();
             }
             this.ProcessResponseStream(responseStream2);
             if (flag)
             {
                 while (mimeReader.ReadNextPart())
                 {
                     int num = 2000;
                     int num2 = num;
                     MimeHeaders mimeHeaders = mimeReader.ReadHeaders(num, ref num2);
                     if (mimeHeaders.ContentID != null && !string.IsNullOrEmpty(mimeHeaders.ContentID.Value))
                     {
                         string text = mimeHeaders.ContentID.Value;
                         if (text.StartsWith("<", StringComparison.Ordinal) && text.EndsWith(">", StringComparison.Ordinal))
                         {
                             text = text.Substring(1, text.Length - 2);
                         }
                         ChunkStreamBuilder chunkStreamBuilder = new ChunkStreamBuilder();
                         chunkStreamBuilder.CopyFrom(mimeReader.GetContentStream());
                         this.Context.AddStream(text, chunkStreamBuilder);
                     }
                 }
             }
             this.m_requestStatus = ClientRequestStatus.CompletedSuccess;
         }
     }
     catch (Exception ex)
     {
         this.m_requestStatus = ClientRequestStatus.CompletedException;
         throw;
     }
     finally
     {
         this.m_context.ProcessingResponse = false;
         this.RequestExecutor.Dispose();
     }
 }
コード例 #31
0
ファイル: MimeReader.cs プロジェクト: Rhombulus/Mime
 public ContentReadStream(MimeReader reader)
 {
     this.reader = reader;
 }
コード例 #32
0
 // Token: 0x06000441 RID: 1089 RVA: 0x00018EE1 File Offset: 0x000170E1
 internal MimeAddressReader(MimeReader reader, bool topLevel)
 {
     this.reader   = reader;
     this.topLevel = topLevel;
 }