public Task BeginDownloadInboxAsync(CancellationToken token) { return(Task.Factory.StartNew(() => { using (var pop3 = new Pop3()) { ConnectAndLogin(pop3); var allUids = pop3.GetAll(); var chunkUids = Common.SplitList(allUids, 5); var builder = new MailBuilder(); foreach (var uids in chunkUids) { var items = new List <EmailItem>(); foreach (var uid in uids) { var bytes = pop3.GetHeadersByUID(uid); IMail email = builder.CreateFromEml(bytes); items.Add(ParseIMail(uid, email)); } ItemsDownloaded?.Invoke(this, items); } } }, token, TaskCreationOptions.LongRunning, TaskScheduler.Default)); }
public async Task <List <Email> > GetPop3EmailHeaders(Model.UserInfo userInfo) { Pop3 pop3 = await ConnectPop3(userInfo); try { if (pop3 != null) { List <string> uids = pop3.GetAll(); MailBuilder builder = new MailBuilder(); foreach (string uid in uids) { var headers = pop3.GetHeadersByUID(uid); IMail mail = builder.CreateFromEml(headers); Email email = new Email { Uid = uid, Date = mail.Date ?? DateTime.MinValue, Subject = mail.Subject, From = string.Join(",", mail.From?.Select(s => s.Address)), }; emailHeaderList.Add(email); } } return(emailHeaderList); } finally { serverConnection.Add(pop3); } }
public override BodyModel GetBody(object uid) { if (uid is string) { if (pop3Connection != null) { MailBuilder builder = new MailBuilder(); var headers = pop3Connection.GetMessageByUID(uid as string); IMail email = builder.CreateFromEml(headers); if (!string.IsNullOrWhiteSpace(email.Html)) { return BodyModel.GetHtmlBody(email.Html); } else if (!string.IsNullOrWhiteSpace(email.Text)) { return BodyModel.GetTextBody(email.Text); } } } else { //TODO: error handling } return null; }
public FetchListServiceResponse <EmailXML> DownloadEmailMessagesFromEmailAccount(EmailDownloadDto emailDownloadDto) { FetchListServiceResponse <EmailXML> response = new FetchListServiceResponse <EmailXML>(); HashSet <EmailXML> emails = new HashSet <EmailXML>(); if ((emailDownloadDto.ServerAddress == "pop.gmail.com" || emailDownloadDto.ServerAddress == "imap.gmail.com") && emailDownloadDto.UseSSL == false) { throw new Exception("Connection to GMAIL requires SSL connection."); } try { using (Imap imap = new Imap()) { imap.Connect(emailDownloadDto.ServerAddress, emailDownloadDto.Port, emailDownloadDto.UseSSL); imap.Login(emailDownloadDto.Username, emailDownloadDto.Password); MailBuilder builder = new MailBuilder(); imap.SelectInbox(); HashSet <long> emailUIDs = new HashSet <long>(imap.GetAll().Take(100)); foreach (long uid in emailUIDs) { IMail emailRaw = builder.CreateFromEml(imap.GetMessageByUID(uid)); EmailXML emailXml = new EmailXML() { InReplyToId = emailRaw.InReplyTo, MessageId = emailRaw.MessageID, Sender = emailRaw.Sender.Address, RawSender = emailRaw.Sender.Name, Sent = emailRaw.Date, Subject = emailRaw.Subject }; emails.Add(emailXml); } imap.Close(); } response.Items = emails; response.Succeeded = true; CreateEmailXMLFile(emails, response); } catch (Exception e) { response.Succeeded = false; throw new Exception($"Download failed with an error: {e.Message}"); } return(response); }
private async Task <bool> ReadPOP3EmailBody(Email email, UserInfo userInfo) { Pop3 pop3 = await ConnectPop3(userInfo); var eml = await Task.Run(() => pop3.GetMessageByUID(email.Uid)); MailBuilder mailbuilder = new MailBuilder(); IMail mail = mailbuilder.CreateFromEml(eml); email.Body = mail.Text; return(true); }
public async Task <bool> GetBody(Email email, UserInfo userInfo) { using Pop3 pop3 = await Connect(userInfo); var eml = await Task.Run(() => pop3.GetMessageByUID(email.Uid)); MailBuilder builder = new MailBuilder(); IMail mail = builder.CreateFromEml(eml); email.Body = mail.Html; return(true); }
public string receivemail(int ShowMailCount) { try { using (Imap imap = new Imap()) { if (MailFrom.Contains("sjtu")) { MailHost = "mail.sjtu.edu.cn"; } else { MessageBox.Show("unknown host"); return(null); } imap.Connect(MailHost); // or ConnectSSL for SSL //Console.WriteLine(MailFrom.Substring(0, MailFrom.IndexOf('@'))); imap.UseBestLogin(MailFrom.Substring(0, MailFrom.IndexOf('@')), MailFromPass); // Receive all messages and display the subject MailBuilder builder = new MailBuilder(); imap.SelectInbox(); List <long> uids = imap.GetAll(); Console.WriteLine(uids.Count); string ret = ""; for (int i = 1; i <= ShowMailCount; ++i) { IMail email = builder.CreateFromEml( imap.GetMessageByUID(uids[uids.Count - i])); // Check signature //if (email.IsSigned == true) // email.CheckSignature(true); //Console.WriteLine(email.Subject); //Console.WriteLine(email.Text); ret += email.Subject + '\n' + email.Text + '\n'; } imap.Close(); return(ret); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } return(null); }
public async IAsyncEnumerable <Email> GetHeaders(UserInfo userInfo, [EnumeratorCancellation] CancellationToken token) { Pop3 pop3 = GetAvailableConnection(); try { if (_stackUids == null) { var uids = await Task.Run(() => pop3.GetAll()); _stackUids = new Stack <string>(uids); } if (_stackUids.Count > 0) { // If scroll is turned on, load only the qty requested by scroll int qtyLoad = !_settings.QtyEmailsByScroll.HasValue ? _stackUids.Count : _settings.QtyEmailsByScroll.Value; MailBuilder builder = new MailBuilder(); for (int i = 1; i <= qtyLoad; i++) { if (_stackUids.TryPop(out string uid)) { var headers = await Task.Run(() => pop3.GetHeadersByUID(uid)); IMail mail = builder.CreateFromEml(headers); Email email = new Email { Uid = uid, Date = mail.Date ?? DateTime.MinValue, Subject = mail.Subject, ListFrom = mail.From.Select(f => $"{f.Name} <{f.Address}>").ToList(), AttachmentsQuantity = mail.Attachments.Count }; yield return(email); } else { break; } } } } finally { _pop3Connections.Enqueue(pop3); } }
public Task <EmailEnvelope> GetHeaderByUID(string messageId) { var builder = new MailBuilder(); var headers = _pop3.GetHeadersByUID(messageId); var email = builder.CreateFromEml(headers); FreeClient(); return(Task.FromResult(new EmailEnvelope() { From = email.From.Select(x => x.Address).ToArray(), Subject = email.Subject, Date = email.Date })); }
private IEnumerable <MailModel> GetMessagesImap(Imap imap) { var builder = new MailBuilder(); var uids = imap.Search(Flag.All); foreach (var email in uids.Select(imap.GetMessageByUID).Select(x => builder.CreateFromEml(x))) { yield return(new MailModel { From = email.From.FormatFromField(), To = string.Join(";", email.To), Date = email.Date?.ToString("G"), Subject = email.Subject, Body = email.Text }); } }
private void button1_Click(object sender, EventArgs e) { using (Imap imap = new Imap()) { imap.ConnectSSL("imap." + client); imap.Login(login, password); CommonFolders folders = new CommonFolders(imap.GetFolders()); imap.Select(folders.Trash); MailBuilder builder = new MailBuilder(); counter = 0; foreach (long uid in imap.Search(Flag.All)) { IMail email = builder.CreateFromEml(imap.GetMessageByUID(uid)); string body = email.Subject + " " + email.Text; canonbody = new List <string>(); canonbody = myCanonize.canonize(body); for (int i = 0; i < canonlist.Count; i++) { for (int j = 0; j < canonbody.Count; j++) { if (myCanonize.LevenshteinDistance(canonlist[i], canonbody[j]) < 3) { values.Add(percentSpam.ElementAt(i)); } } } double spam = myBayes.CBayes(values); if (spam > 0.3) { listBox2.Items.Add(body + myBayes.CBayes(values)); } else { listBox1.Items.Add(body); } values.Clear(); } } }
private void GetHeader(string uid) { lock (EmailList) { var emailView = EmailList[uid.ToString()]; lock (pop) { MailBuilder builder = new MailBuilder(); var headers = pop.GetHeadersByUID(uid); IMail email = builder.CreateFromEml(headers); EmailViewManager.SetHeader(ref emailView, email.From.First().Name, email.Subject, email.Date?.ToString("MM/dd/yyyy hh:mm:ss")); ListChanged = true; } } }
public override EnvelopeModel GetEnvelope(object uid) { if(uid is string) { if (pop3Connection != null) { MailBuilder builder = new MailBuilder(); var headers = pop3Connection.GetHeadersByUID(uid as string); IMail email = builder.CreateFromEml(headers); return new EnvelopeModel(email, uid as string); } } else { //TODO: error handling } return null; }
private void GetBody(string uid) { lock (EmailList) { var emailView = EmailList[uid.ToString()]; if (emailView.Text == null) { lock (pop) { MailBuilder builder = new MailBuilder(); IMail email = builder.CreateFromEml( pop.GetMessageByUID(uid)); EmailViewManager.SetBody(ref emailView, email.Text, email.Html); ListChanged = true; } } } }
private void Form2_Load(object sender, EventArgs e) { using (Imap imap = new Imap()) { imap.ConnectSSL("imap." + client); imap.Login(login, password); CommonFolders folders = new CommonFolders(imap.GetFolders()); imap.Select(folders.Spam); MailBuilder builder = new MailBuilder(); counter = 0; foreach (long uid in imap.Search(Flag.All)) { counter++; IMail email = builder.CreateFromEml(imap.GetMessageByUID(uid)); string text = email.Subject + " " + email.Text; List <string> canontext = myCanonize.canonize(text); foreach (string row in canontext) { if (row == "") { continue; } if (!tokens.ContainsKey(row)) { tokens.Add(row, 1); } else { tokens[row]++; } } } tokens = tokens.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value); for (int i = 0; i < 15; i++) { canonlist.Add(tokens.ElementAt(i).Key); percentSpam.Add(Convert.ToDouble(tokens.ElementAt(i).Value) * 100 / Convert.ToDouble(counter)); } } }
public Task <EmailBody> GetBodyByUID(string messageId) { var builder = new MailBuilder(); var message = _pop3.GetMessageByUID(messageId); var email = builder.CreateFromEml(message); var attachments = email?.Attachments? .Select(x => new EmailAttachment() { Id = x.ContentId, Name = x.SafeFileName }).ToArray(); FreeClient(); return(Task.FromResult(new EmailBody { Text = email.Text, Html = email.Html, Attachments = attachments })); }
public static List <IMail> GetNext5Emails(ServerType serverType, string server, int port, bool useSSL, string login, string password) { var messages = new List <IMail>(); if (ConfigurationManager.AppSettings["DisableMailChecker"] != null) { return(messages); //debug setting from web.config... used this to move to a new server... don't mind } if (serverType == ServerType.POP) { using (var popClient = GetPopClient(server, port, useSSL, login, password)) { MailBuilder builder = new MailBuilder(); foreach (var uid in popClient.GetAll().Take(5)) { var msg = builder.CreateFromEml(popClient.GetMessageByUID(uid)); messages.Add(msg); popClient.DeleteMessageByUID(uid); } popClient.Close(); } } else //imap { using (var client = GetImapClient(server, port, useSSL, login, password)) { var uids = client.Search(Flag.Unseen).Take(5); foreach (var uid in uids) { var msg = new MailBuilder().CreateFromEml(client.GetMessageByUID(uid)); messages.Add(msg); client.DeleteMessageByUID(uid); } } } return(messages); }
private async Task <bool> ReadPop3EmailBody(Pop3 pop3, Model.Email email) { return(await Task.Run(() => { lock (email) { if (string.IsNullOrEmpty(email.Body)) { var msg = pop3.GetMessageByUID(email.Uid); MailBuilder builder = new MailBuilder(); IMail mail = builder.CreateFromEml(msg); email.Body = mail.Text; if (mail.Attachments != null) { // show attachment in email and when user clicks the attachment it should download saveAttachmentToDisk(email.Uid, pop3); } return true; } return false; } })); }
public static IMail Clone(this IMail source) { var builder = new MailBuilder(); return(builder.CreateFromEml(source.Render())); }
public int GetMails(short idBox, Boolean IsProtocolBox, string boxRecipient, Func <string, string, bool> headerExistHandler, string defaultSubject) { MailBuilder builder = new MailBuilder(); var counter = 0; using (Imap mailClient = CreateMailClient()) { List <long> mails = GetMailsUids(mailClient, Pars.ImapSearchFlag, Pars.ImapStartDate, Pars.ImapEndDate); for (int messageCounter = mails.Count - 1; messageCounter >= 0 && counter < Pars.MaxMailsForSession; messageCounter--) { if (Pars.UserCanceled()) { return(counter); } long uid = mails[messageCounter]; LogAction(string.Format("Get Headers Mail Uid:{0}", uid)); byte[] headers = mailClient.GetHeadersByUID(uid); string headerHash = headers.ComputeSHA256Hash(); // Verifico se già presente, controlla header hash MessageInfo info = mailClient.GetMessageInfoByUID(uid); LogAction(String.Format("Check Header Checksum Mail Uid:{0} / Subject:{1} / Data:{2}", uid, info.Envelope.Subject, info.Envelope.Date)); if (headerExistHandler(headerHash, boxRecipient)) { LogAction(String.Format("Mail Uid:{0} - Skipped", uid)); //TODO: inserire logica di 'eliminazione o identificare la pec come già presente continue; } //controlla se ho già scaricata nel drop folder if (MailInfo.CheckMailExist(Pars.DropFolder, headerHash)) { //TODO: inserire logica di 'emilinazione o identificare la pec come già presente continue; } string outpathEml, outpathXml; Utils.GetDropFilenames(Pars.DropFolder, out outpathEml, out outpathXml); //mail info MailInfo mInfo = new MailInfo { Client = MailInfo.ClientType.Imap, EmlFilename = outpathEml, IDPECMailBox = idBox, IsProtocolBox = IsProtocolBox, MailBoxRecipient = boxRecipient, MailUID = uid.ToString(CultureInfo.InvariantCulture) }; IMail email = builder.CreateFromEml(headers); mInfo.Parse(email); mInfo.Body = DownloadBody(mailClient, info); mInfo.Size = GetMailSize(info); mInfo.SaveAs(outpathXml); //download eml LogAction("Download Mail Uid:" + uid); byte[] eml = mailClient.GetMessageByUID(uid); File.WriteAllBytes(outpathEml, eml); //salva eml hash del messaggio mInfo.HeaderHash = headerHash; mInfo.EmlHash = eml.ComputeSHA256Hash(); mInfo.UpdateStatus(MailInfo.ProcessStatus.Downloaded); mInfo.Save(); counter++; } mailClient.Close(); return(counter); } }
public int GetMails(short idBox, Boolean IsProtocolBox, string boxRecipient, Func <string, string, bool> headerExistHandler, string defaultSubject) { var builder = new MailBuilder(); var counter = 0; using (Pop3 mailClient = CreateMailClient()) { var currentStats = mailClient.GetAccountStat(); for (var messageCounter = (int)currentStats.MessageCount; messageCounter > 0 && counter < Pars.MaxMailsForSession; messageCounter--) { if (Pars.UserCanceled()) { return(counter); } var uid = mailClient.GetUID(messageCounter); LogAction("Get Headers Mail Uid:" + uid); byte[] headers = mailClient.GetHeadersByUID(uid); string headerHash = headers.ComputeSHA256Hash(); // Verifico se già presente, controlla header hash var email = builder.CreateFromEml(headers); LogAction(string.Format("Check Headers Mail Uid:{0} / Subject:{1} / Data:{2}", uid, email.Subject, email.Date)); if (headerExistHandler(headerHash, boxRecipient)) { continue; } //controlla se ho già scaricata nel drop folder if (MailInfo.CheckMailExist(Pars.DropFolder, headerHash)) { continue; } string outpathEml, outpathXml; Utils.GetDropFilenames(Pars.DropFolder, out outpathEml, out outpathXml); //mail info MailInfo mInfo = new MailInfo { Client = MailInfo.ClientType.Pop3, EmlFilename = outpathEml, IDPECMailBox = idBox, IsProtocolBox = IsProtocolBox, MailBoxRecipient = boxRecipient, MailUID = uid }; mInfo.Parse(email); mInfo.Body = "#"; mInfo.Size = GetMailSize(mailClient, messageCounter); mInfo.SaveAs(outpathXml); //download eml LogAction("Download Mail Uid:" + uid); byte[] eml = mailClient.GetMessageByUID(uid); File.WriteAllBytes(outpathEml, eml); //Aggiorna il Body //Pop3 deve forzatamente scaricare l'intero messaggio per ottenere il body della mail email = builder.CreateFromEml(eml); mInfo.HeaderHash = headerHash; mInfo.EmlHash = eml.ComputeSHA256Hash(); mInfo.Body = email.GetBodyAsHtml(); mInfo.UpdateStatus(MailInfo.ProcessStatus.Downloaded); mInfo.Save(); counter++; } return(counter); } }
private void StartReceiveMail() { if (string.IsNullOrEmpty(Settings.Default.MailInput_Server)) { Logger.WriteDebug("MailService: Server not set -> stop receive"); return; } if (Settings.Default.MailInput_Port <= 0) { Logger.WriteDebug("MailService: Port not set -> stop receive"); return; } if (string.IsNullOrWhiteSpace(Settings.Default.MailInput_User)) { Logger.WriteDebug("MailService: User not set -> stop receive"); return; } if (string.IsNullOrWhiteSpace(Settings.Default.MailInput_Password)) { Logger.WriteDebug("MailService: Password not set -> stop receive"); return; } _receiveMailTaskTokenSource = new CancellationTokenSource(); _nextMailTaskRestartTime = DateTime.Now.AddMinutes(1); _receiveMailTask = Task.Factory.StartNew(() => { _receiveMailTaskTokenSource.Token.ThrowIfCancellationRequested(); Logger.WriteDebug("MailService.receiveTask: start"); try { //Check settings using (var imapClient = new Imap()) { Logger.WriteDebug(MethodBase.GetCurrentMethod(), "Connect to IMAP-Server..."); //Connect try { if (Settings.Default.MailInput_SSL) { imapClient.ConnectSSL(Settings.Default.MailInput_Server, Settings.Default.MailInput_Port); } else { imapClient.Connect(Settings.Default.MailInput_Server, Settings.Default.MailInput_Port); } imapClient.UseBestLogin(Settings.Default.MailInput_User, Encrypt.DecryptString(Settings.Default.MailInput_Password, "MailInput_Password")); Logger.WriteDebug(MethodBase.GetCurrentMethod(), "Connect -> ok"); } catch (Exception ex) { ExceptionOccured.RaiseEvent(this, new ExceptionEventArgs { Methode = MethodBase.GetCurrentMethod(), Error = ex }); _receiveMailTaskMonitorTimer?.Stop(); _receiveMailTaskTokenSource?.Cancel(); return; } //Chech IDLE command if (!imapClient.SupportedExtensions().Contains(ImapExtension.Idle)) { Logger.WriteDebug(MethodBase.GetCurrentMethod(), "Server does not support imap idle -> abort"); return; } //Select standart Inbox as folder imapClient.SelectInbox(); //Thread to recognize stop command and stop idle command Task.Factory.StartNew(() => { Logger.WriteDebug("MailService.idelTask: start"); while (!_receiveMailTaskTokenSource.Token.IsCancellationRequested) { Thread.Sleep(1000); } imapClient.StopIdle(); Logger.WriteDebug("MailService.idelTask: stop"); }, _receiveMailTaskTokenSource.Token); //Thread hangs until new mail or stop while (!_receiveMailTaskTokenSource.Token.IsCancellationRequested) { Logger.WriteDebug(MethodBase.GetCurrentMethod(), "imap idle -> start"); var currentStatus = imapClient.Idle(); Logger.WriteDebug(MethodBase.GetCurrentMethod(), "imap idle -> finished"); if (_receiveMailTaskTokenSource.Token.IsCancellationRequested) { break; } //Create expression var _searchExpression = Expression.HasFlag(Flag.Unseen); if (!string.IsNullOrWhiteSpace(Settings.Default.MailInput_Subject)) { _searchExpression = Expression.And(Expression.Subject(Settings.Default.MailInput_Subject), Expression.HasFlag(Flag.Unseen)); } //Query messages uids foreach (var uid in imapClient.Search(_searchExpression)) { Logger.WriteDebug(MethodBase.GetCurrentMethod(), $"message UID -> {uid}"); imapClient.MarkMessageSeenByUID(uid); var mailBuilder = new MailBuilder(); mailBuilder.CreatePlainTextAutomatically = true; var emlMessage = imapClient.GetMessageByUID(uid); var mail = mailBuilder.CreateFromEml(emlMessage); if (mail.Attachments.Count >= 1) { Logger.WriteDebug(MethodBase.GetCurrentMethod(), $"message attachments -> {mail.Attachments.Count}"); // save all attachments to disk var attachmentId = 1; foreach (var mime in mail.Attachments) { mime.Save(Path.Combine(Settings.Default.Fax_PathInput, $"ALARMMAIL-ATTACHMENT-{attachmentId}_{Guid.NewGuid()}{Path.GetExtension(mime.SafeFileName)}")); Logger.WriteDebug(MethodBase.GetCurrentMethod(), $"message attachment [{mime.SafeFileName}] -> saved"); attachmentId++; } } else { Logger.WriteDebug(MethodBase.GetCurrentMethod(), $"message text -> {mail.Text}"); if (string.IsNullOrWhiteSpace(mail.Text)) { Logger.WriteDebug(MethodBase.GetCurrentMethod(), "message text is empty -> abort"); continue; } //Write message to txt file File.WriteAllText( Path.Combine(Settings.Default.Fax_PathInput, $"ALARMMAIL_{Guid.NewGuid()}.txt"), mail.Text, Encoding.GetEncoding(1252)); //Raise EinsatzCreated MailReceived.RaiseEvent(this, new MailReceivedEventArgs(mail.Text)); } } } //Disconnect imapClient.Close(); } } catch (Exception ex) { ExceptionOccured.RaiseEvent(this, new ExceptionEventArgs { Methode = MethodBase.GetCurrentMethod(), Error = ex }); } Logger.WriteDebug("MailService.receiveTask: stop"); }, _receiveMailTaskTokenSource.Token); //Start task monitor if mail task is running if (_receiveMailTask != null && _receiveMailTask.Status == TaskStatus.Running) { Logger.WriteDebug("MailService.receiveMailTaskMonitorTimer: start"); _receiveMailTaskMonitorTimer = new Timer(); _receiveMailTaskMonitorTimer.Elapsed += receiveMailTaskMonitorTimer_Elapsed; _receiveMailTaskMonitorTimer.Interval = 5000; _receiveMailTaskMonitorTimer.Start(); } }
static public string getmsgemail(string Steamlogin) { using (Pop3 pop3 = new Pop3()) { if (Config.emailssl == true) { try { pop3.ConnectSSL(Config.emailserver); } catch (Exception e) { errorlog(e.Message); return(null); } } else { try { pop3.Connect(Config.emailserver); } catch (Exception e) { errorlog(e.Message); return(null); } } try { pop3.UseBestLogin(Config.emaillogin, Config.emailpassword); } catch (Exception e) { errorlog(e.Message); return(null); } MailBuilder builder = new MailBuilder(); foreach (string uid in pop3.GetAll()) { IMail email = builder.CreateFromEml( pop3.GetMessageByUID(uid)); long unixTime = (long)(email.Date.Value - new DateTime(1970, 1, 1)).TotalSeconds; long epochTicks = new DateTime(1970, 1, 1).Ticks; long unixfTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond) + 10800; long unixffTime = unixfTime - unixTime; if (unixffTime <= 300) { string text1 = getBetween(email.Text, Steamlogin.ToLower() + ":", "This email was generated because"); if (text1 != null) { return(text1.Replace("\r\n", string.Empty) .Replace("\n", string.Empty) .Replace("\r", string.Empty)); } } } errorlog("Не могу найти письмо!"); return(null); } }