/// <summary> /// Get mail using POP3 Mail Protocol /// </summary> /// <param name="folderName">Current Folder / Name of DataTable</param> /// <param name="emailCount">Count of email in folder</param> /// <param name="increment">Current Index</param> /// <param name="worker">BackgroundWorker that started this thread</param> private void GetMailUsingPOP3(string folderName, int increment, BackgroundWorker worker) { List <string> emails = _pop3.GetAll(); foreach (string uid in emails) { // If top 5 perfect of emails, then download. if (float.Parse(uid) >= 42000f) { // Add new row to DataTable DataRow emailDataRow = _emailDataTableList[increment].NewRow(); IMail emailData = new MailBuilder() .CreateFromEml(_pop3.GetMessageByUID(uid)); // This takes just as long cause it downloads entire messages either way emailDataRow["GUID"] = uid; emailDataRow["Date"] = emailData.Date.ToString(); emailDataRow["From"] = emailData.From; emailDataRow["Body"] = emailData.GetBodyAsHtml(); emailDataRow["Subject"] = emailData.Date.ToString() + " - " + emailData.Subject; emailDataRow["Viewed"] = 0; _emailDataTableList[increment].Rows.Add(emailDataRow); } } _emailContent.Tables.Add(_emailDataTableList[increment]); //add data table if there is none in DS yet. _emailContent.Tables.Remove(folderName); }
public static void GetDataFromMail() { string dataDir = GetDataDir_Emails(); string dataDirAtt = GetDataDir_Attachments(); using (Imap imap = new Imap()) { EmailItem item = new EmailItem(); try { imap.Connect("imap.gmail.com", 993, true); imap.UseBestLogin(Username, Password); imap.SelectInbox(); List <long> uids = imap.Search(Flag.Unseen); int count = 0; if (uids.Count > 0) { foreach (long uid in uids) { IMail email = new MailBuilder().CreateFromEml(imap.GetMessageByUID(uid)); var eml = imap.GetMessageByUID(uid); item.Subject = email.Subject; item.MessageID = email.MessageID; item.Date = Convert.ToDateTime(email.Date); item.Content = email.GetBodyAsHtml(); item.Path = dataDir + email.MessageID + ".eml"; string filename = string.Format(dataDir + item.MessageID + ".eml", uid); File.WriteAllBytes(filename, eml); foreach (MailAddress cc in email.Cc) { foreach (MailBox mailbox in cc.GetMailboxes()) { item.Cc.Add(mailbox.Address); } } int emailID = Email.InsertEmail(item); if (emailID > 0) { foreach (MimeData SaveAttachment in email.Attachments) { AttachmentItem AttachmentItem = new AttachmentItem(); Guid g = Guid.NewGuid(); while (Email.GUIDIsExist(g.ToString())) { g = Guid.NewGuid(); } AttachmentItem.GUID = Convert.ToString(g); AttachmentItem.EmailID = emailID; AttachmentItem.AttachmentName = SaveAttachment.FileName; AttachmentItem.ContentType = Convert.ToString(SaveAttachment.ContentType).ToLower(); AttachmentItem.Size = Convert.ToInt64(SaveAttachment.Size); AttachmentItem.Path = dataDirAtt + AttachmentItem.GUID + "-" + SaveAttachment.SafeFileName; if (Email.InsertAttachment(AttachmentItem)) { SaveAttachment.Save(dataDirAtt + AttachmentItem.GUID + "-" + SaveAttachment.SafeFileName); } else { Console.WriteLine("Fail to download attachment."); } } count++; Console.WriteLine(" - Inserted email " + item.Subject + " - " + item.Date); imap.MarkMessageSeenByUID(uid); imap.GmailLabelMessageByUID(uid, FolderFlag.XStarred.Name); } } Console.WriteLine("--Download " + count + " emails completed--"); imap.Close(); } } catch { Console.WriteLine("Internet problem occured.Please check your internet connection."); Thread.Sleep(5000); GetDataFromMail(); } } }
public void Process(string dropFolder, int biblosMaxLength) { string step = string.Empty; try { string filePrefix = GetPrefix(EmlFilename); //crea una cartella temporanea con la desinenza del nome del file eml string tempFolder = Path.Combine(dropFolder, filePrefix); step = string.Format("Creazione Temp Folder: '{0}'", tempFolder); //se esiste svuota if (Directory.Exists(tempFolder)) { Directory.Delete(tempFolder, true); } Directory.CreateDirectory(tempFolder); string indexFile = Path.Combine(dropFolder, string.Format("{0}_index.xml", filePrefix)); fileIndex = indexFile; EmlProcessor processor = new EmlProcessor(biblosMaxLength); step = string.Format("Elaborazione Eml: '{0}'", EmlFilename); XElement indexRoot = processor.ProcessFile(EmlFilename, tempFolder); indexRoot.Save(indexFile); MailIndexFile index = MailIndexFile.Load(indexFile); //attachment particolari //body di primo livello MailAttachmentFile attachment = index.files.FirstOrDefault(p => p.isBody && p.idParent == 0); if (attachment != null) { fileBody = attachment.Filename; } //postacert.eml int postacertId = 0; attachment = index.files.FirstOrDefault(p => p.Filename.ToLower().EndsWith("postacert.eml") && p.idParent == 0); if (attachment != null && attachment.mimeType == MimeType.Message.Name && attachment.mimeSubtype == MimeSubtype.Rfc822.Name) { step = string.Format("Elaborazione '{0}'", attachment.Filename); IMail email = new MailBuilder().CreateFromEmlFile(attachment.Filename); ParsePostacert(email); Body = email.GetBodyAsHtml(); filePostacert = attachment.Filename; postacertId = attachment.id; } //daticert.xml attachment = index.files.FirstOrDefault(p => p.Filename.ToLower().EndsWith("daticert.xml") && p.idParent == 0); if (attachment != null && attachment.mimeType == MimeType.Application.Name && attachment.mimeSubtype == MimeSubtype.Xml.Name) { step = string.Format("Elaborazione '{0}'", attachment.Filename); fileDaticert = attachment.Filename; } //smime.p7s attachment = index.files.FirstOrDefault(p => p.Filename.ToLower().EndsWith("smime.p7s") && p.idParent == 0); if (attachment != null && attachment.mimeType == MimeType.Application.Name && attachment.mimeSubtype == MimeSubtype.XPkcs7Signature.Name) { step = string.Format("Elaborazione '{0}'", attachment.Filename); fileSMime = attachment.Filename; } //segnatura.xml //cerca tra i figli di postacert.eml if (postacertId > 0) { attachment = index.files.FirstOrDefault(p => p.Filename.ToLower().EndsWith("segnatura.xml") && p.idParent == postacertId); if (attachment != null) { step = string.Format("Elaborazione '{0}'", attachment.Filename); fileSegnatura = attachment.Filename; } } //salva informazioni step = string.Format("Salva MailInfo in '{0}'", sourceFile); UpdateStatus(ProcessStatus.Processed); Save(); } catch (Exception ex) { string message = string.Format("Errore in ProcessFile:'{0}' step:{1}, Exception:{2}", sourceFile, step, ex.Message); AddError(message, ex); Save(); throw new ApplicationException(LastError(), ex); } }
/// <summary> /// Get mail using IMAP Mail Protocol /// </summary> /// <param name="folderName"></param> /// <param name="emailCount"></param> /// <param name="increment"></param> /// <param name="worker"></param> private void GetMailUsingIMAP(string folderName, int increment, BackgroundWorker worker, int totalFolderCount) { _imap.Select(folderName); int percentComplete = 0; bool alreadyOwn = false; List <long> emailList = _imap.GetAll(); int inc = 0; foreach (int uid in emailList) { DataRow emailDataRow; if (_getNewMessages) { worker.ReportProgress(50); emailDataRow = _emailContent.Tables[folderName].NewRow(); } else { emailDataRow = _emailDataTableList[increment].NewRow(); } alreadyOwn = false; if (_emailContent.Tables.Count > 0) { for (int x = 0; x < _emailContent.Tables[increment].Rows.Count; x++) { if (_emailContent.Tables[increment].Rows[x][0].ToString() == uid.ToString()) { alreadyOwn = true; } } } if (alreadyOwn == false) { var eml = _imap.GetMessageByUID(uid); IMail emailData = new MailBuilder() .CreateFromEml(eml); emailDataRow["GUID"] = uid; emailDataRow["Date"] = emailData.Date.ToString(); emailDataRow["From"] = emailData.From; emailDataRow["Body"] = emailData.GetBodyAsHtml(); emailDataRow["Subject"] = emailData.Date.ToString() + " - " + emailData.Subject; emailDataRow["Viewed"] = 1; if (_getNewMessages) { worker.ReportProgress(100); _emailContent.Tables[increment].Rows.Add(emailDataRow); } else { _emailDataTableList[increment].Rows.Add(emailDataRow); } } percentComplete = (inc * 100 / emailList.Count); worker.ReportProgress(percentComplete); inc++; } if (!_getNewMessages) { _emailContent.Tables.Add(_emailDataTableList[increment]); //add data table if there is none in DS yet. } }