示例#1
0
 public static Task SendMessageAsync(
     this IImapMessageChannel channel,
     ImapMessage message,
     CancellationToken cancellationToken)
 {
     return(channel.SendMessageAsync(message, DefaultEncoding, cancellationToken));
 }
        public static DataContact[] ToDataContact(this ImapMessage msg, uint id)
        {
            var list = new List <DataContact>();

            foreach (var contact in msg.To)
            {
                list.Add(new DataContact()
                {
                    ContactName  = contact.ContactName,
                    ContactType  = ContactTypes.To,
                    EmailAddress = contact.EmailAddress,
                    MessageId    = id,
                });
            }
            foreach (var contact in msg.Cc)
            {
                list.Add(new DataContact()
                {
                    ContactName  = contact.ContactName,
                    ContactType  = ContactTypes.Cc,
                    EmailAddress = contact.EmailAddress,
                    MessageId    = id,
                });
            }
            list.Add(new DataContact()
            {
                ContactName  = msg.From.ContactName,
                ContactType  = ContactTypes.From,
                EmailAddress = msg.From.EmailAddress,
                MessageId    = id,
            });
            return(list.ToArray());
        }
        public async Task <Email> SaveEmailAsync(ImapMessage imapMessage)
        {
            var sha       = _hashProvider.ToSha256(imapMessage.MimeMessageBytes);
            var timestamp = imapMessage.ReceivedAtUTC.ToString("yyyyMMddHHmmss");
            var filename  = $"{timestamp}_{imapMessage.From?.EmailAddress ?? "NULL"}_{sha.Substring(0, 16)}";

            var attachments = imapMessage.Attachments.Select(x => new Attachment
            {
                FileName = x.Filename,
            }).ToList();

            var email = new Email
            {
                Body            = string.IsNullOrEmpty(imapMessage.Body) ? imapMessage.BodyPlainText : imapMessage.Body,
                Subject         = imapMessage.Subject,
                AttachmentCount = imapMessage.Attachments.Length,
                Sha256          = sha,
                FileName        = filename,
                FolderName      = imapMessage.MailFolder,
                FromAddress     = imapMessage.From?.EmailAddress ?? "NULL",
                ReceivedAt      = imapMessage.ReceivedAtUTC,
                UniqueId        = Convert.ToInt32(imapMessage.UId),
                Attachments     = attachments
            };

            _dbContext.Emails.Add(email);
            await _dbContext.SaveChangesAsync();

            return(email);
        }
示例#4
0
        public void Run(IInteractDispatcher dispatcher)
        {
            ReceiveHeader header = new ReceiveHeader(this._uid, true, this._attchmentDirectory);

            header.Interact(dispatcher);
            this._message = header.MessageCollection[0];
            new ReceivePart(this._message, this._message.RootPart, this._attchmentDirectory).Interact(dispatcher);
        }
示例#5
0
        public void AddItem(ImapMessage messageDescription, string itemKey, byte[] itemValue, string attachmentDirectory, string uid)
        {
            string str;

            itemKey = itemKey.ToLower();
            switch (itemKey)
            {
            case "flags":
                if (messageDescription.Header.Date == DateTime.MinValue &&
                    string.IsNullOrEmpty(messageDescription.Header.MessageID) &&
                    messageDescription.Header.From == null &&
                    messageDescription.Header.To.Count == 0)
                {
                    IEnumerable <MessageFlag> collection = this.ParseMessageFlagCollection(Net.Imap.Parsers.Utils.Unparenthesis(itemValue));
                    messageDescription.Flags.AddRange(collection);
                }
                return;

            case "rfc822.size":
                str = this.DefaultEncoding.GetString(itemValue, 0, itemValue.Length);
                messageDescription.Size = uint.Parse(str);
                return;

            case "body":
                messageDescription.RootPart = new BodyPartDescriptionParser().Parse(Net.Imap.Parsers.Utils.Unparenthesis(itemValue), attachmentDirectory);
                return;

            case "body[header]":
                messageDescription.Header = new MIMEHeaderParser().Parse(this.DefaultEncoding.GetString(itemValue, 0, itemValue.Length));
                return;
            }
            messageDescription.Uid = uid;
            Match match = new Regex(@"body\[(?<index>[\d\.]+)\]").Match(itemKey);

            if (match.Success)
            {
                IPart part = messageDescription.FindPart(match.Groups["index"].Value);
                if (part.Type == EPartType.Text)
                {
                    TextPart part2   = (TextPart)part;
                    string   charset = part2.Header.ContentType.Attributes.ContainsKey("charset") ? part2.Header.ContentType.Attributes["charset"] : "us-ascii";
                    part2.Text = new SimplePartContentParser().Parse(itemValue, part2.Header.ContentTransferEncoding, charset);
                }
                else if (part.Type == EPartType.Message)
                {
                    MessagePart              part3          = (MessagePart)part;
                    MemoryStream             incomingStream = new MemoryStream(itemValue);
                    SizedMessageStreamReader reader         = new SizedMessageStreamReader(incomingStream, (uint)itemValue.Length);
                    part3.Message = new MailMessageParser().Parse(reader, uid, attachmentDirectory);
                }
            }
            match = new Regex(@"body\[(?<index>[0-9\.]+)\.mime\]").Match(itemKey);
            if (match.Success)
            {
                messageDescription.FindPart(match.Groups["index"].Value).Header = new MIMEHeaderParser().Parse(this.DefaultEncoding.GetString(itemValue, 0, itemValue.Length));
            }
        }
示例#6
0
        public async Task CommandCompletedAsync(
            ImapMessage message,
            IImapCommand command,
            CancellationToken cancellationToken)
        {
            await SendPendingResponsesAsync(cancellationToken);

            await this.SendMessageAsync(message, cancellationToken);
            await EndCommandWithoutResponseAsync(command, cancellationToken);
        }
示例#7
0
        protected override CompletionResponse Behaviour()
        {
            MessageDescriptionParser parser  = new MessageDescriptionParser();
            StringBuilder            builder = new StringBuilder();
            int           num         = 0;
            List <string> subPartList = (this._partDescription == null ? new List <string>()
            {
                ""
            } : this.GetSubPartList(this._partDescription));

            for (int i = 0; i < subPartList.Count; i++)
            {
                if (i > 0)
                {
                    builder.Append(" ");
                }
                builder.Append(string.Format("BODY.PEEK[{0}]", subPartList[i]));
            }
            uint          commandId = base._dispatcher.SendCommand(string.Format("UID FETCH {0} ({1})", this._message.Uid, builder), base.filter);
            IMAP4Response response  = base._dispatcher.GetResponse(commandId);

            if (!response.IsCompletionResponse())
            {
                if (response.Name != "FETCH")
                {
                    throw new UnexpectedResponseException("Unexpected response");
                }
                string input = response.Data.Substring(response.Data.IndexOf("(") + 1);
                while (num < subPartList.Count)
                {
                    Regex regex = new Regex(@"[\}]*{(?<size>[0-9]+)}|(?<size>NIL)");
                    if (!regex.IsMatch(input))
                    {
                        throw new Exception("Unexpected response");
                    }
                    string s = regex.Match(input).Groups["size"].Value;
                    num++;
                    if (!s.Equals("NIL", StringComparison.OrdinalIgnoreCase))
                    {
                        ulong  size             = ulong.Parse(s);
                        byte[] rawData          = base._dispatcher.GetRawData(size);
                        byte[] bytes            = Encoding.UTF8.GetBytes(input + "\r\n");
                        byte[] destinationArray = new byte[bytes.Length + rawData.Length];
                        Array.Copy(bytes, destinationArray, bytes.Length);
                        Array.Copy(rawData, 0, destinationArray, bytes.Length, rawData.Length);
                        this._message = parser.Parse(this._message, destinationArray, this._message.Uid, this._attachmentDirectory);
                        byte[] rawDataBytes = base._dispatcher.GetRawData();
                        input = Encoding.UTF8.GetString(rawDataBytes, 0, rawDataBytes.Length);
                    }
                }
                response = base._dispatcher.GetResponse(commandId);
            }
            return(new CompletionResponse(response.Response));
        }
        public void Run(IInteractDispatcher dispatcher)
        {
            ReceiveMessageText text = new ReceiveMessageText(this._uid, this._attachmentDirectory);

            text.Run(dispatcher);
            this._message = text.Message;
            foreach (Attachment attachment in this._message.Attachments)
            {
                new ReceiveAttach(this._message, attachment, this._attachmentDirectory).Interact(dispatcher);
            }
        }
示例#9
0
        public ImapMessage Parse(byte[] source, string uid, string attachmentDirectory)
        {
            ImapMessage sourceMessage = new ImapMessage();

            this.Parse(sourceMessage, source, uid, attachmentDirectory);
            if (sourceMessage.RootPart != null)
            {
                sourceMessage.InitializeInternalStructure();
            }
            return(sourceMessage);
        }
示例#10
0
        public static Task ReportBadAsync(
            IImapMessageChannel imapSession,
            string tag,
            string errorText,
            CancellationToken cancellationToken)
        {
            var message = new ImapMessage(tag, "BAD", new List <IMessageData> {
                new ServerMessageData(errorText)
            });

            return(imapSession.SendMessageAsync(message, DefaultEncoding, cancellationToken));
        }
示例#11
0
        public ImapMessage Parse(ImapMessage sourceMessage, byte[] source, string uid, string attachmentDirectory)
        {
            List <byte[]> list = Net.Imap.Parsers.Utils.ExtractParams(source);

            if ((list.Count % 2) != 0)
            {
                throw new FormatException("The source string was not in a correct format");
            }
            for (int i = 0; i < list.Count; i += 2)
            {
                this.AddItem(sourceMessage, this.DefaultEncoding.GetString(list[i], 0, list[i].Length), list[i + 1], attachmentDirectory, uid);
            }
            sourceMessage.FillText();
            return(sourceMessage);
        }
示例#12
0
        public static DataAttachment[] ToAttachment(this ImapMessage msg, uint id)
        {
            var list = new List <DataAttachment>();

            foreach (var att in msg.Attachments)
            {
                list.Add(new DataAttachment()
                {
                    FileContent = att.FileContent,
                    Filename    = att.Filename,
                    MessageId   = id,
                });
            }
            return(list.ToArray());
        }
示例#13
0
        bool ShowMessage(ImapMessage msg, MessageListInfo info)
        {
            info.Index++;

            if (msg != null)
            {
                // If From property is empty then use the Sender property.
                string from = msg.From.ToString();
                if (from.Length == 0 && msg.Sender != null)
                {
                    from = msg.Sender.ToString();
                }
                string[] arr = new string[]
                {
                    from, msg.Subject, msg.Date != null?msg.Date.ToString() : "1/1/1900",
                        (msg.Flags & ImapMessageFlags.Deleted) != 0 ? "Delete" : string.Empty, Util.FormatSize(msg.Size)
                };
                ListViewItem item = new ListViewItem(arr);
                if ((msg.Flags & ImapMessageFlags.Seen) == 0)
                {
                    // New message.
                    item.Font       = new Font(item.Font, item.Font.Style | FontStyle.Bold);
                    item.ImageIndex = 2;
                }
                else
                {
                    // Seen message.
                    item.ImageIndex = 3;
                }
                item.Tag = new ListItemTagInfo(msg.MessageInboxIndex, msg.UniqueId, msg.ReceivedDate, msg.Size);

                // Add to the list.
                listView.Items.Add(item);
                // Update the status text.
                toolStripProgressLabel.Text = string.Format("{0}/{1} message(s) retrieved", info.Index, info.List.Count);
            }
            else
            {
                toolStripProgressBar.Maximum--;
            }

            if (info.Index < toolStripProgressBar.Maximum)
            {
                toolStripProgressBar.Value = info.Index;
            }

            return(info.Index < info.List.Count);
        }
示例#14
0
        void DownloadImapMessage(MessageListInfo info)
#endif
        {
Retry:

            ImapMessage m = info.List[info.Index];

            if (_cancelling)
            {
                return;
            }

#if Framework4_5
            ImapMessage msg = null;
            try
            {
                // Retrieve message information.
                msg = await client.DownloadImapMessageAsync(m.UniqueId, ImapEnvelopeParts.Envelope);
            }
            catch (Exception ex)
            {
                if (!HandleException(ex))
                {
                    return;
                }
            }

            ShowMessage(msg, info);

            if (_state == ConnectionState.Disconnecting)
            {
                Disconnect();
                return;
            }

            if (!_cancelling && info.Index < info.List.Count)
            {
                goto Retry;
            }

            EnableProgress(false, 0);
            // Update the state.
            listView_SelectedIndexChanged(null, null);
#else
            client.DownloadImapMessageAsync(m.UniqueId, ImapEnvelopeParts.Envelope, info);
#endif
        }
        public void ParticipantsRFC2047Decoded()
        {
            const string EncodedDisplayName = "=?utf-8?B?5YiY5YWL5bOw?=";
            const string EncodedUser = "******";
            const string EncodedHost = "someplace.com";

            const string ExpectedDecodedDisplayName = "刘克峰";

            const string Input = "* 54 FETCH (X-GM-MSGID 1379514999738475089 UID 79 FLAGS () ENVELOPE (\"Fri, 9 Sep 2011 15:38:52 -0700\" \"Simple message\" ((\"" + EncodedDisplayName + "\" NIL \"" + EncodedUser + "\" \"" + EncodedHost + "\")) ((\"" + EncodedDisplayName + "\" NIL \"" + EncodedUser + "\" \"" + EncodedHost + "\")) ((\"" + EncodedDisplayName + "\" NIL \"" + EncodedUser + "\" \"" + EncodedHost + "\")) ((NIL NIL \"tyler.austen.test1\" \"gmail.com\")) NIL NIL NIL \"<00a801cc6f41$408cd2f0$c1a678d0$@com>\") BODYSTRUCTURE ((\"TEXT\" \"PLAIN\" (\"CHARSET\" \"us-ascii\") NIL NIL \"7BIT\" 18 2 NIL NIL NIL)(\"TEXT\" \"HTML\" (\"CHARSET\" \"us-ascii\") NIL NIL \"QUOTED-PRINTABLE\" 1657 47 NIL NIL NIL) \"ALTERNATIVE\" (\"BOUNDARY\" \"----=_NextPart_000_00A9_01CC6F06.942DFAF0\") NIL NIL))";

            var list = ImapList.Parse(Input);
            var message = new ImapMessage(long.Parse(list.GetStringAt(1)), list.GetListAt(3));

            var sender = message.From;

            Assert.AreEqual(sender.DisplayName, ExpectedDecodedDisplayName);
        }
示例#16
0
 public static DataMessage ToData(this ImapMessage msg, uint emailAccountId)
 {
     return(new DataMessage()
     {
         Body = msg.Body,
         BodyPlainText = msg.BodyPlainText,
         HasAttachments = msg.HasAttachments,
         InReplyToId = msg.InReplyToId,
         MailFolder = msg.MailFolder,
         MessageTextId = msg.MessageTextId,
         MimeMessageBytes = msg.MimeMessageBytes,
         ReceivedAtLocal = msg.ReceivedAtLocal,
         ReceivedAtUTC = msg.ReceivedAtUTC,
         Subject = msg.Subject,
         FromAddress = msg.From?.EmailAddress,
         UId = msg.UId,
         EmailAccountId = emailAccountId,
     });
 }
示例#17
0
        public async Task SendMessageAsync(ImapMessage message, Encoding encoding, CancellationToken cancellationToken)
        {
            using (await SemaphoreLock.GetLockAsync(_sendSemaphore, cancellationToken))
            {
                var builder = new StringBuilder();
                builder.Append(message.Tag);
                foreach (IMessageData data in message.Data)
                {
                    if (data is LiteralMessageData literal)
                    {
                        builder.Append("}");
                        builder.Append(literal.Length);
                        builder.AppendLine("}");
                        await _connection.WriteAsync(builder.ToString(), encoding, cancellationToken);

                        builder.Clear();
                    }
                    else
                    {
                        if (builder.Length > 0)
                        {
                            builder.Append(" ");
                        }

                        builder.Append(data.ToMessageString());
                    }
                }

                if (builder.Length > 0)
                {
                    _logger.Verbose("IMAP -> " + builder);
                    builder.AppendLine();
                    await _connection.WriteAsync(builder.ToString(), encoding, cancellationToken);
                }
            }
        }
示例#18
0
        protected override CompletionResponse Behaviour()
        {
            Exception     exception        = null;
            IPart         partByAttachment = this._message.GetPartByAttachment(this._attachmentDescription);
            uint          commandId        = base._dispatcher.SendCommand(string.Format("UID FETCH {0} (BODY.PEEK[{1}] BODY.PEEK[{1}.MIME])", this._message.Uid, this._message.GetPartIndex(partByAttachment)), base.filter);
            IMAP4Response response         = base._dispatcher.GetResponse(commandId);

            while (!response.IsCompletionResponse())
            {
                if (response.Name != "FETCH")
                {
                    throw new UnexpectedResponseException("Unexpected response");
                }
                ulong             size   = base.GetSize(response);
                FileContentWriter writer = new FileContentWriter(this._attachmentDirectory);
                try
                {
                    writer.Open();
                    string str = string.Empty;
                    while (size > 0L)
                    {
                        ulong  num3  = (size > 0x1000L) ? ((ulong)0x1000L) : size;
                        byte[] bytes = base._dispatcher.GetRawData(num3);
                        byte[] data  = bytes;
                        if (partByAttachment.Header.ContentTransferEncoding == EContentTransferEncoding.Base64)
                        {
                            string str2 = str + Encoding.UTF8.GetString(bytes, 0, bytes.Length).Replace("\r\n", "");
                            data = Convert.FromBase64String(str2.Substring(0, str2.Length - (str2.Length % 4)));
                            str  = str2.Substring(str2.Length - (str2.Length % 4));
                        }
                        writer.Write(data);
                        size -= num3;
                    }
                }
                catch (Exception exception2)
                {
                    exception = exception2;
                    base._dispatcher.GetRawData(size);
                }
                finally
                {
                    writer.Close();
                }
                this._attachmentDescription.DiskFilename = writer.Filename;
                byte[] rawData = base._dispatcher.GetRawData();
                string s       = Encoding.UTF8.GetString(rawData, 0, rawData.Length) + "\r\n";
                rawData = Encoding.UTF8.GetBytes(s);
                Match match = new Regex("{(?<size>[0-9]+)}|(?<size>NIL)").Match(s);
                if (match.Success && (match.Groups["size"].Value != "NIL"))
                {
                    size = ulong.Parse(match.Groups["size"].Value);
                    byte[] sourceArray      = base._dispatcher.GetRawData(size);
                    byte[] destinationArray = new byte[rawData.Length + sourceArray.Length];
                    Array.Copy(rawData, destinationArray, rawData.Length);
                    Array.Copy(sourceArray, 0, destinationArray, rawData.Length, sourceArray.Length);
                    this._message = new MessageDescriptionParser().Parse(this._message, destinationArray, this._message.Uid, this._attachmentDirectory);
                    base._dispatcher.GetRawData();
                }
                response = base._dispatcher.GetResponse(commandId);
            }
            if (exception != null)
            {
                throw exception;
            }
            return(new CompletionResponse(response.Response));
        }
示例#19
0
 public ReceiveAttach(ImapMessage message, Attachment attachmentDescription, string attachmentDirectory)
 {
     this._message = message;
     this._attachmentDescription = attachmentDescription;
     this._attachmentDirectory   = attachmentDirectory;
 }
示例#20
0
        private static void DumpMessageInfo(ImapMessage m)
        {
            const string ItemFormat = "\t{0}:\t{1}";
            System.Console.WriteLine("==========");
            System.Console.WriteLine("MSG UID [{0}]:", m.Uid);
            System.Console.WriteLine(ItemFormat, "Subj.", m.Subject);
            System.Console.WriteLine(ItemFormat, "Sender", m.Sender.ToString());
            System.Console.WriteLine(ItemFormat, "Date", m.Timestamp.ToString());
            if (null != m.ExtensionParameters && m.ExtensionParameters.Count > 0)
            {
                System.Console.WriteLine(ItemFormat, "Extension Parameters:", string.Empty);
                const string ExtensionParamFormat = "\t" + ItemFormat;
                foreach (var paramName in m.ExtensionParameters.Keys)
                {
                    string paramValue = StringifyExtensionParamValue(m.ExtensionParameters[paramName]);

                    System.Console.WriteLine(ExtensionParamFormat, paramName, paramValue);
                }
            }
            System.Console.WriteLine("----------");
        }
示例#21
0
 public AttachReceivedArgs(ImapMessage message, Attachment attachmentDescription)
 {
     this._message = message;
     this._attachmentDescription = attachmentDescription;
 }
 public MessageReceivedEventArgs(ImapMessage message)
 {
     this._message = message;
 }
示例#23
0
 public ReceivePart(ImapMessage message, IPart partDescription, string attachmentDirectory)
 {
     this._message             = message;
     this._partDescription     = partDescription;
     this._attachmentDirectory = attachmentDirectory;
 }