/// <summary> /// 将邮件保存到草稿箱 返回邮件的唯一标识 /// 调用前先调用配置方法CfgIMAP(),调用制做邮件方法 /// </summary> public int SaveDrafts(int uniqueId = -1) { try { using (ImapClient client = ConnectIMAP()) { // 打开草稿箱,添加邮件 IMailFolder folder = client.GetFolder(SpecialFolder.Drafts); folder.Open(FolderAccess.ReadWrite); // 如果保存的是已经有的草稿邮件,则删除它再保存新的草稿.(没找到保存已有草稿的办法) if (uniqueId > -1) { List <UniqueId> uidls = new List <UniqueId>(); uidls.Add(new UniqueId((uint)uniqueId)); folder.SetFlags(uidls, MessageFlags.Seen | MessageFlags.Deleted, true); folder.Expunge(uidls); } UniqueId?uid = folder.Append(this.message, MessageFlags.Seen | MessageFlags.Draft); // folder.Close(); client.Disconnect(true); return(uid.HasValue ? (int)uid.Value.Id : -1); } } catch (Exception e) { ErrMsg = $"邮件保存草稿时异常:{e.ToString()} [{e.Message}]"; return(-1); } }
private UniqueId GetUniqueId(MimeMessage mailMessage, string folder) { UniqueId id = new UniqueId(); IMailFolder mailFolder = GetFolder(folder); bool open = mailFolder.IsOpen; if (!open) { mailFolder.Open(FolderAccess.ReadOnly); } var items = mailFolder.Fetch(0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.Size | MessageSummaryItems.Flags); foreach (var item in items) { var message = mailFolder.GetMessage(item.UniqueId); if (message.MessageId == mailMessage.MessageId) { id = item.UniqueId; break; } } if (!open) { mailFolder.Close(); } return(id); }
/// <summary> /// 邮件添加标识(已读,已回复,已删除等等).参数值参考EmailViewM实体同名属性 /// 调用前先调用配置方法CfgIMAP() /// </summary> /// <param name="uniqueIdls">同一文件夹下的邮件唯一标识列表</param> /// <param name="flag">标识代码 1=已读 2=已回复 8=删除</param> /// <param name="folderType">文件夹名</param> public void SetFlag(List <uint> uniqueIdls, int flag, string folderType = null) { try { using (ImapClient client = ConnectIMAP()) { List <UniqueId> uniqueids = uniqueIdls.Select(o => new UniqueId(o)).ToList(); MessageFlags messageFlags = (MessageFlags)flag; if (folderType == null) { folderType = client.Inbox.Name; } IMailFolder folder = client.GetFolder(folderType); folder.Open(FolderAccess.ReadWrite); folder.AddFlags(uniqueids, messageFlags, true); // folder.Close(); client.Disconnect(true); } } catch (Exception e) { ErrMsg = $"邮件添加标识时异常:{e.ToString()} [{e.Message}]"; } }
public Folder(IMailFolder imapFolder) { _imapFolder = imapFolder; _imapFolder.Open(FolderAccess.ReadOnly); NumberOfMessages = _imapFolder.Count; _imapFolder.Close(); }
/// <summary> /// 根据唯一标识和文件夹名,获取单个邮件 /// </summary> /// <param name="folderName"></param> /// <returns></returns> public EmailViewM GetEmailByUid(uint uniqueid, string folderName = null) { try { using (ImapClient client = ConnectIMAP()) { if (folderName == null) { folderName = client.Inbox.Name; } IMailFolder folder = client.GetFolder(folderName); folder.Open(FolderAccess.ReadOnly); var email = folder.GetMessage(new UniqueId(uniqueid)); var entity = FillEntity(null, email); // folder.Close(); client.Disconnect(true); // return(entity); } } catch (Exception e) { ErrMsg = $"获取单个邮件异常:{e.ToString()} [{e.Message}]"; return(null); } }
public IList <Tuple <string, string> > GetBasicInfo(string folder, int page, int pageSize) { List <Tuple <string, string> > Info = new List <Tuple <string, string> >(); if (!IsAuthenticated()) { return(Info); } IMailFolder mailFolder = GetFolder(folder); mailFolder.Open(FolderAccess.ReadWrite); var Items = mailFolder.Fetch((page - 1) * pageSize, pageSize, MessageSummaryItems.UniqueId | MessageSummaryItems.Size | MessageSummaryItems.Flags | MessageSummaryItems.All); if (Items == null) { Items = new List <IMessageSummary>(); } foreach (var mail in (Items as List <MessageSummary>)) { Info.Add(new Tuple <string, string>(mail.NormalizedSubject, mail.Envelope.From[0].Name)); } mailFolder.Close(); return(Info); }
public void GetAllMails(IProgress <MailInfo> progress, [Optional] IMailFolder folder) { using (ImapClient client = new ImapClient()) { client.Connect(mailServer, port, ssl); client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(UserData.Email, UserData.Password); if (folder == null) { folder = client.Inbox; } else { folder = client.GetFolder(folder.FullName); } folder.Open(FolderAccess.ReadOnly); SearchResults results = folder.Search(SearchOptions.All, SearchQuery.DeliveredAfter(DateFrom)); if (results.UniqueIds.Count < MaxEmails) { MaxEmails = results.UniqueIds.Count; } for (int i = MaxEmails - 1; i >= 0; i--) { MailInfo message = new MailInfo(folder.GetMessage(results.UniqueIds[i]), results.UniqueIds[i], folder); progress.Report(message); } folder.Close(); client.Disconnect(true); } }
public static void RemoveFolder(IMailFolder folder, Configuration config) { using var kernel = new FakeItEasyMockingKernel(); kernel.Rebind <ILogger>().ToConstant(Log.Logger); kernel.Rebind <Configuration>().ToConstant(config); kernel.Rebind <ImapStore>().ToSelf().InSingletonScope(); kernel.Rebind <ImapConnectionFactory>().ToSelf().InSingletonScope(); var imapFac = kernel.Get <ImapConnectionFactory>(); using var connection = imapFac.GetImapConnectionAsync().Result; var subFolders = folder.GetSubfolders(); foreach (var subFolder in subFolders) { RemoveFolder(subFolder, config); } folder.Open(FolderAccess.ReadWrite); var allMessages = folder.Search(SearchQuery.All); folder.SetFlags(allMessages, MessageFlags.Deleted, true); folder.Expunge(); folder.Close(); try { folder.Delete(); } catch (Exception e) { Debug.WriteLine("Exception while deleting folder: " + e.ToString()); } connection.Disconnect(true); }
public void CopyFolder(IMailFolder folder, Folder sqlEntity, bool update, string password) { try { folder.Open(FolderAccess.ReadOnly); } catch (Exception) { return; } Random rng = AzusaContext.GetInstance().RandomNumberGenerator; IList <UniqueId> uuids = folder.Search(FolderService.GetSearchQuery(sqlEntity)); foreach (UniqueId uuid in uuids) { if (MessageService.TestForMessage((int)uuid.Id)) { continue; } var message = folder.GetMessage(uuid); byte[] saltBuffer = new byte[16]; rng.NextBytes(saltBuffer); Array.Copy(azusaString, 0, saltBuffer, 0, azusaString.Length); int iterations = rng.Next(1000, short.MaxValue); Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, saltBuffer, iterations); Aes aes = Aes.Create(); aes.Key = deriveBytes.GetBytes(32); aes.IV = deriveBytes.GetBytes(16); MemoryStream ms = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write); message.WriteTo(cryptoStream); cryptoStream.Flush(); Mail child = new Mail(); child.Uid = (int)uuid.Id; child.MessageUtime = message.Date.DateTime.ToUnixTime(); child.Folder = sqlEntity.id; child.From = message.From[0].ToString(); if (message.To.Count > 0) { child.To = message.To[0].ToString(); } else { child.To = null; } child.Subject = message.Subject; child.Salt = saltBuffer; child.Iterations = (short)iterations; child.Data = new byte[ms.Position]; Array.Copy(ms.GetBuffer(), 0, child.Data, 0, ms.Position); MessageService.StoreMessage(child); } folder.Close(false); }
private void CloseCurrentFolder() { if (_currentFolder != null) { _currentFolder.Close(false); _currentFolder = null; } }
internal IEnumerable <Message> GetMessages() { _imapFolder.Open(FolderAccess.ReadOnly); var messages = _imapFolder.Search(SearchQuery.All).Select(u => new Message(u, _imapFolder.GetHeaders(u))).ToArray(); _imapFolder.Close(); return(messages); }
public void ReOpen(IMailFolder folder, FolderAccess folderAccess) { if (folder.IsOpen) { folder.Close(); } folder.Open(folderAccess); }
public void reloadMessages(string folder) { IMailFolder mailFolder = GetFolder(folder); mailFolder.Open(FolderAccess.ReadWrite); _currentFolderSummary = mailFolder.Fetch(0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.Flags | MessageSummaryItems.Envelope); mailFolder.Close(); _currentFolder = folder; }
public Tuple <IList <Mail>, HttpStatusCode> GetMailsFromFolder(string folder, int page, int pageSize, string sortOrder) { if (!IsAuthenticated()) { return(new Tuple <IList <Mail>, HttpStatusCode>(null, HttpStatusCode.ExpectationFailed)); } if (folder != _currentFolder) { reloadMessages(folder); } List <Mail> Mails = new List <Mail>(); if (_currentFolderSummary == null) { _currentFolderSummary = new List <IMessageSummary>(); } switch (sortOrder) { case "dateAsc": _currentFolderSummary = _currentFolderSummary.OrderBy(mail => mail.Date.DateTime); break; case "subjectDesc": _currentFolderSummary = _currentFolderSummary.OrderByDescending(mail => mail.NormalizedSubject); break; case "subjectAsc": _currentFolderSummary = _currentFolderSummary.OrderBy(mail => mail.NormalizedSubject); break; case "senderDesc": _currentFolderSummary = _currentFolderSummary.OrderByDescending(mail => mail.Envelope.From[0]); break; case "senderAsc": _currentFolderSummary = _currentFolderSummary.OrderBy(mail => mail.Envelope.From[0]); break; default: _currentFolderSummary = _currentFolderSummary.OrderByDescending(mail => mail.Date.DateTime); break; } IMailFolder mailFolder = GetFolder(folder); mailFolder.Open(FolderAccess.ReadWrite); foreach (var mail in _currentFolderSummary.Skip((page - 1) * pageSize).Take(pageSize)) { Mails.Add(new Mail((MessageSummary)mail, mailFolder.GetMessage(mail.UniqueId), folder)); } mailFolder.Close(); return(new Tuple <IList <Mail>, HttpStatusCode>(Mails, HttpStatusCode.OK)); }
public List <MailItem> ExtractMailItems(IMailFolder folder, int pageSize, int page, List <uint> existingUids) { try { using (var client = new ImapClient()) { Connect(client); if (!folder.IsOpen) { logger.LogTrace("Open Folder"); folder.Open(FolderAccess.ReadOnly); } logger.LogInformation($"Fetch summaries [{folder.FullName}] - \tPage: {page} - Page Size: {pageSize}"); var summaries = folder.Fetch(page * pageSize, (page + 1) * pageSize - 1, MessageSummaryItems.UniqueId); logger.LogInformation($"Got summaries [{folder.FullName}] - Count: {summaries.Count}"); if (summaries.Count == 0) { return(null); } var result = new List <MailItem>(); logger.LogTrace("Extract Mail Addresses"); foreach (var summary in summaries) { if (!existingUids.Contains(summary.UniqueId.Id)) { var message = folder.GetMessage(summary.UniqueId); result.AddRange(CreateMailItems(logger, message, this, folder, summary.UniqueId)); } } if (folder.IsOpen) { logger.LogTrace("Close Folder"); folder.Close(false); } return(result); } } catch (Exception e) { logger.LogError(e, $"Error in folder: {folder.FullName} \r\n {e.Message}"); return(null); } }
private void CopyMessages(IMailFolder folder, IMailFolder dest) { try { folder.Open(FolderAccess.ReadOnly); dest.Open(FolderAccess.ReadWrite); UniqueIdRange r = new UniqueIdRange(UniqueId.MinValue, UniqueId.MaxValue); var headers = new HashSet <HeaderId>(); headers.Add(HeaderId.Received); headers.Add(HeaderId.Date); headers.Add(HeaderId.MessageId); headers.Add(HeaderId.Subject); headers.Add(HeaderId.From); headers.Add(HeaderId.To); headers.Add(HeaderId.Cc); headers.Add(HeaderId.ResentMessageId); var msgList = folder.Fetch(r, MessageSummaryItems.UniqueId | MessageSummaryItems.InternalDate | MessageSummaryItems.Flags, headers); int total = msgList.Count; int i = 1; foreach (var msg in msgList) { Console.WriteLine($"Copying {i++} of {total}"); CopyMessage(msg, folder, dest); if (i % 100 == 0) { dest.Check(); } } } finally { folder.Close(); dest.Close(); } }
private static void OutputFolder(OutputTable output, IMailFolder folder, ref int messages, ref int unread, int indent = 0) { var a = folder.Open(FolderAccess.ReadOnly); output.AddRow("".PadRight(indent) + folder.Name, folder.Count, folder.Unread); var q = folder.GetQuota(); messages += folder.Count; unread += folder.Unread; folder.Close(); foreach (var subFolder in folder.GetSubfolders()) { OutputFolder(output, subFolder, ref messages, ref unread, indent + 1); } }
public void MarkAsUnRead(MailInfo mail) { using (ImapClient client = new ImapClient()) { client.Connect(mailServer, port, ssl); client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(UserData.Email, UserData.Password); IMailFolder folder = client.GetFolder(mail.ParentFolder.FullName); folder.Open(FolderAccess.ReadWrite); folder.RemoveFlags(new List <UniqueId> { mail.Uid }, MessageFlags.Seen, true); folder.Close(); client.Disconnect(true); } }
public HttpStatusCode MarkEmailAsUnread(UniqueId id, string folder) { if (!IsAuthenticated()) { return(HttpStatusCode.ExpectationFailed); } IMailFolder mailFolder = GetFolder(folder); if (mailFolder != null) { mailFolder.Open(FolderAccess.ReadWrite); mailFolder.RemoveFlags(id, MessageFlags.Seen, true); mailFolder.Close(); return(HttpStatusCode.OK); } else { return(HttpStatusCode.InternalServerError); } }
public int TryVisitFolder( IMailFolder folder, Action <List <UniqueId>, List <UniqueId> > onCompletion) { try { return(VisitFolder(folder, onCompletion)); } catch (ImapCommandException commandException) { Console.WriteLine("Failed to open folder {0}. {1}", folder.Name, commandException.Message); return(0); } finally { try { folder.Close(); } catch (Exception) { } // ignore - it's ok if the folder was already closed; we just want to ensure that it is closed. } }
/// <summary> /// 使用唯一ID获取一封完整邮件 /// 调用前先调用配置方法CfgIMAP() /// </summary> /// <param name="folder">文件夹名,默认是收件箱</param> /// <param name="uniqueid">邮件唯一编号</param> public EmailViewM GetEmailByUniqueId(uint uniqueid, string folderName = null) { try { using (ImapClient client = ConnectIMAP()) { if (folderName == null) { folderName = client.Inbox.Name; } IMailFolder folder = client.GetFolder(folderName); folder.Open(FolderAccess.ReadWrite); UniqueId emailUniqueId = new UniqueId(uniqueid); // 获取这些邮件的摘要信息 List <UniqueId> uids = new List <UniqueId>(); uids.Add(emailUniqueId); var emaills = folder.Fetch(uids, MessageSummaryItems.UniqueId | MessageSummaryItems.Envelope); var emhead = emaills[0]; // 获取邮件含正文部分,. MimeMessage embody = folder.GetMessage(emailUniqueId); /*赋值到实体类*/ var entity = FillEntity(emhead, embody, folder); //然后设置为已读 folder.AddFlags(emailUniqueId, MessageFlags.Seen, true); // folder.Close(); client.Disconnect(true); // return(entity); } } catch (Exception e) { ErrMsg = $"获取单个完整邮件异常:{e.ToString()} [{e.Message}]"; return(null); } }
static void Main(string[] args) { // Load command line and text file info about connection + keywords EmailInfo settings = new EmailInfo(args); // Pull emails and email indicides for all unread emails IList <UniqueId> newEmailIds; IMailFolder emails = settings.GetNewEmails(out newEmailIds); // Exit program if no new emails were found if (newEmailIds.Count == 0) { Console.WriteLine("No new emails!"); return; } // Extract Retrospect non-error messages and update indices IList <UniqueId> successfulEmailIds = settings.GetSuccessful(emails, newEmailIds); // Get Ids of everything that is not an successful retrospect email IList <UniqueId> errorOrUniqueIds = newEmailIds.Except(successfulEmailIds).ToList <UniqueId>(); // Get Ids of every retrospect error message IList <UniqueId> errorIds = settings.GetFailure(emails, errorOrUniqueIds); // Get Ids of everything that is not a retrospect email IList <UniqueId> uniqueIds = errorOrUniqueIds.Except(errorIds).ToList <UniqueId>(); // Notify admin of all unique and error emails, using supplied outgoing server info EmailSender sender = new EmailSender(args); sender.SendEmails(QueryManipulation.ExtractMessages(emails, errorIds), QueryManipulation.ExtractMessages(emails, uniqueIds), successfulEmailIds.Count); // Close inbox emails.Close(); }
public Tuple <IList <string>, HttpStatusCode> GetSubjectsFromFolder(string folder, int page, int pageSize) { if (!IsAuthenticated()) { return(new Tuple <IList <string>, HttpStatusCode>(null, HttpStatusCode.ExpectationFailed)); } IMailFolder mailFolder = GetFolder(folder); if (mailFolder == null) { return(new Tuple <IList <string>, HttpStatusCode>(new List <string>(), HttpStatusCode.InternalServerError)); } mailFolder.Open(FolderAccess.ReadWrite); IList <string> Subjects = new List <string>(); for (int i = page * pageSize; i < mailFolder.Count && i < pageSize; i++) { var message = mailFolder.GetMessage(i); Subjects.Insert(0, message.Subject); } mailFolder.Close(); return(new Tuple <IList <string>, HttpStatusCode>(Subjects, HttpStatusCode.OK)); }
public Tuple <Mail, HttpStatusCode> GetMailFromFolder(UniqueId id, string folder) { if (!IsAuthenticated()) { return(new Tuple <Mail, HttpStatusCode>(null, HttpStatusCode.ExpectationFailed)); } IMailFolder mailFolder = GetFolder(folder); mailFolder.Open(FolderAccess.ReadWrite); var Items = mailFolder.Fetch(new List <UniqueId>() { id }, MessageSummaryItems.UniqueId | MessageSummaryItems.Size | MessageSummaryItems.Flags | MessageSummaryItems.All); if (Items == null) { Items = new List <IMessageSummary>(); } Mail mail = new Mail((MessageSummary)Items.First(), mailFolder.GetMessage(Items.First().UniqueId), folder); mailFolder.Close(); return(new Tuple <Mail, HttpStatusCode>(mail, HttpStatusCode.OK)); }
public void StarEmail(MailInfo mail) { using (ImapClient client = new ImapClient()) { client.Connect(mailServer, port, ssl); client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(UserData.Email, UserData.Password); IMailFolder folder = client.GetFolder(mail.ParentFolder.FullName); folder.Open(FolderAccess.ReadWrite); var folders = client.GetFolders(new FolderNamespace('/', "[Gmail]")); foreach (var item in folders) { if (item.FullName.Equals(@"[Gmail]/Csillagozott") || item.FullName.Equals(@"[Gmail]/Starred")) { folder.MoveTo(mail.Uid, client.GetFolder(item.FullName)); } } folder.Close(); client.Disconnect(true); } }
private void MailCheck() { DBConnect conn = new DBConnect(); SqlConnection sqlConnection = new SqlConnection(@"Data Source=" + conn.host + ";Initial Catalog=" + conn.db + ";" + "User ID=" + conn.user + ";Password="******"SELECT * FROM Mails WHERE Send_from = '{message.From.ToString().Replace("'","")}' " + $"and Subject = '{message.Subject.ToString().Replace("'", "")}' and Send_to = '{message.To.ToString().Replace("'", "")}'"; bool kostyl = false; using (DbDataReader reader = sqlCommand.ExecuteReader()) { if (!reader.HasRows) { kostyl = true; } } if (kostyl) { SqlCommand command = sqlConnection.CreateCommand(); command.CommandText = "INSERT INTO Mails (Send_from, Subject, Date_send, Send_to, Importance, isRead) " + $"VALUES ('{message.From.ToString().Replace("'","")}', '{message.Subject.ToString().Replace("'", "")}', " + $"'{message.Date.ToString().Replace("'", "")}', '{message.To.ToString().Replace("'", "")}', 'Важное', 0)"; command.ExecuteNonQuery(); inbox.AddFlags(item.UniqueId, MessageFlags.Deleted, true); inbox.Expunge(); } } inbox.Close(); } } catch (Exception ex) { Logger.Log.Error(ex.ToString()); } finally { sqlConnection.Close(); sqlConnection.Dispose(); } }