private void DeleteEmails() { foreach (var account in LoadAccounts()) { _logger.InfoFormat("Deleting emails from account: {0}", account.User); using (var client = new Pop3()) { client.Connect(_popHost, _popPort, _popUseSsl); client.UseBestLogin(account.User, account.Password); var stats = client.GetAccountStat(); long loopLimit = _batchSizePerAccount; if (stats.MessageCount < loopLimit) loopLimit = stats.MessageCount; for (var i = 1; i <= loopLimit; i++) { var email = new MailBuilder().CreateFromEml(client.GetMessageByNumber(i)); if(email.Date.HasValue && DateTime.Now.Subtract(email.Date.Value).TotalDays > _deleteEmailsOlderThanDays) { client.DeleteMessageByNumber(i); } } } } }
public Pop3MailBeeClient() { Pop3.LicenseKey = MailBeeEmailClient.MAILBEE_LICENSE_KEY; // Make sure to disable throwing exception explicitly. Otherwise strange things might happen. See bug #5748 for details. // So please don't change this option unless you know what you are doing!!! _client = new Pop3 { ThrowExceptions = false }; }
public void FetchMessages(NameValueCollection param) { Pop3 client = new Pop3(); bool connected = false; try { string outdir = RequireParam("outdir", param); if (!Directory.Exists(outdir)) Directory.CreateDirectory(outdir); string server = RequireParam("server", param); int port = Convert.ToInt32(RequireParam("port", param)); string ssl = param["ssl"]; if (ssl.Length == 0) ssl = port == 995 ? "1" : "0"; TlsParameters par = new TlsParameters(); par.CommonName = server; par.CertificateVerifier = CertificateVerifier.AcceptAll; Pop3Security sec = (Pop3Security)Enum.Parse(typeof(Pop3Security), RequireParam("security", param)); log.Info("Connecting to {0}:{1}. SSL: {2}", server, port, ssl); string sess = client.Connect(server, port, par, sec); connected = true; log.Info("Connected: {0}", sess); Pop3Authentication auth = (Pop3Authentication)Enum.Parse(typeof(Pop3Authentication), RequireParam("auth", param)); log.Info("Logging in: {0}", RequireParam("user", param)); client.Login(RequireParam("user", param), RequireParam("pwd", param), auth); log.Info("Logged in."); Pop3MessageCollection messages = client.GetMessageList(); log.Info("There are {0} messages", messages.Count); int maxcount = Convert.ToInt32(RequireParam("maxcount", param)); if (maxcount <= 0 || maxcount > messages.Count) maxcount = messages.Count; for (int i = 0; i < maxcount; i++) { Pop3MessageInfo mi = messages[i]; log.Info("Downloading message {0}", mi.SequenceNumber); MailMessage mm = client.GetMailMessage(mi.SequenceNumber); log.Info("Message from: {0}, to: {1}, subject: {2}", mm.From, mm.To, mm.Subject); string g = Guid.NewGuid().ToString(); string file = Path.Combine(outdir, g + ".eml"); log.Info("Saving message to {0}", file); mm.Save(file); client.Delete(mi.SequenceNumber); } bool rollback = !"0".Equals(RequireParam("noremove", param)); client.Disconnect(rollback); } catch (Exception ex) { if (connected) client.Disconnect(true); throw; } }
static void Main() { using (Pop3 pop3 = new Pop3()) { pop3.Connect(_server); // Use overloads or ConnectSSL if you need to specify different port or SSL. pop3.Login(_user, _password); // You can also use: LoginAPOP, LoginPLAIN, LoginCRAM, LoginDIGEST methods, // or use UseBestLogin method if you want Mail.dll to choose for you. List<string> uidList = pop3.GetAll(); // Get unique-ids of all messages. foreach (string uid in uidList) { IMail email = new MailBuilder().CreateFromEml( // Download and parse each message. pop3.GetMessageByUID(uid)); ProcessMessage(email); // Display email data, save attachments. } pop3.Close(); } }
internal int Pop3Check() { try { var pop3Settings = new Pop3Settings(); var obj = new Pop3(); obj.Connect(pop3Settings.Host, pop3Settings.Username, pop3Settings.Password, pop3Settings.Port); string KeyWord = Helpers.Xml.AppConfigQuery("jaNET/System/Comm/MailKeyword").Item(0).InnerText; foreach (Pop3Message msg in obj.List()) { Pop3Message msg2 = obj.Retrieve(msg); /*Console.WriteLine("Message {0}: {1}", * msg2.number, msg2.message);*/ if (msg2.Message.Contains("<" + KeyWord + ">")) { //If a command found to mail subject Match Command = Regex.Match(msg2.Message.Replace("\r\n", " "), @"(<" + KeyWord + ">)(.*?)(?=</" + KeyWord + ">)"); Command.ToString().ToLower().Replace("<" + KeyWord + ">", string.Empty).Parse(); obj.Delete(msg2); } else { //For Future Use /*Match From = Regex.Match(msg2.message, @"(?<=From: )(.*?)(?= <)"); * Match Subject = Regex.Match(msg2.message, @"(?<=Subject: )(.*?)(?=\\r\\nDate: )"); //(?<=Subject:</B> )(.*?)(?=</)"); * MailList.Add("From " + From.ToString() + ", Subject " + Subject.ToString());*/ //From pattern (?<=From: \\\")(.*?)(?=\\\") //Subject pattern (?<=Subject: )(.*?)(?=\\r) } } obj.Disconnect(); return(obj.List().Count); } catch { return(0); } }
public Pop3Client(string username, string password, string server, int port, EncryptionType encryptionType) : base(username, encryptionType) { _pop3 = new Pop3(); if (encryptionType == EncryptionType.SSLTLS) { _pop3.ConnectSSL(server, port); } else { _pop3.Connect(server, port); if (encryptionType == EncryptionType.StartTLS) { _pop3.StartTLS(); } } _pop3.Login(username, password); }
private bool GetAllMessages(Pop3 pop) { try { MailMessageCollection messages = pop.DownloadEntireMessages(); foreach (MailMessage message in messages) { if (AddToList(message)) { pop.DeleteMessage(message.IndexOnServer); } } return(true); } catch (Exception ex) { _lastError = ex.Message; } return(false); }
void loginmail() { try { clientmail = new SmtpClient("smtp.gmail.com", 587); pop3 = new Pop3(); pop3.ConnectSSL("pop.gmail.com", 995); clientmail.EnableSsl = true; clientmail.Credentials = new NetworkCredential(textBox_gmailSend.Text, textBox_password.Text); pop3.Login(textBox_gmailSend.Text, textBox_password.Text); MessageBox.Show(" Tài khoản đăng nhập thành công", "Đăng nhập hệ thống", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show("Đăng nhập thất bại", "Đăng nhập hệ thống", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.ToString()); } }
private async Task <Pop3> Connect(UserInfo userInfo) { var timeout = _settings.ConnectionTimeOutMilliseconds; Task timeoutTask = Task.Delay(timeout); var connectionTask = Task.Run(() => { Pop3 pop3 = _pop3Factory.GetInstance(); if (userInfo.EncryptionType == Model.Enum.EncryptionType.Unencrypted) { pop3.Connect(userInfo.Server, userInfo.Port); } else if (userInfo.EncryptionType == Model.Enum.EncryptionType.SslTls) { pop3.ConnectSSL(userInfo.Server, userInfo.Port); } else { pop3.Connect(userInfo.Server, userInfo.Port); pop3.StartTLS(); } pop3.UseBestLogin(userInfo.UserName, userInfo.Password); return(pop3); }); var completedTask = await Task.WhenAny(connectionTask, timeoutTask); if (completedTask == connectionTask) { return(await connectionTask); } else { throw new TimeoutException("Connection with the server timed out"); } }
public async Task OpenConnection(Model.UserInfo userInfo) { _pop3Connections = new ConcurrentQueue <Pop3>(); // At least one connection opened is enough for start GetHeaders Pop3 pop3 = await Connect(userInfo); _pop3Connections.Enqueue(pop3); // Run the others in background, no need to await Task.Run(async() => { int countSuccess = 0; int countFailure = 0; // Subtract one, already created above while (countSuccess < _settings.Pop3MultipleConnections - 1) { try { Pop3 pop3 = await Connect(userInfo); _pop3Connections.Enqueue(pop3); countSuccess++; countFailure = 0; } catch (Exception) { countFailure++; // Try again until be able to open the requested number of paralell connections if (countFailure >= _settings.MaxConnectionFailures) { break; } } } }); }
private void saveAttachmentToDisk(string selectedmailuid, Pop3 pop3) { List <string> uids = pop3.GetAll(); foreach (string uid in uids) { if (uid.ToString() == selectedmailuid.ToString()) { var eml = pop3.GetMessageByUID(uid); IMail email = new MailBuilder() .CreateFromEml(eml); ReadOnlyCollection <MimeData> attachments = email.ExtractAttachmentsFromInnerMessages(); string emailAttachmentPath = Path.Combine(Environment.CurrentDirectory, "LocalData"); // save all attachments to disk foreach (MimeData mime in attachments) { mime.Save(emailAttachmentPath + mime.SafeFileName); } } } }
private void button1_Click(object sender, EventArgs e) { using (Pop3 pop3 = new Pop3()) { pop3.Connect("mail.invoicedigital.cl"); // or ConnectSSL for SSL pop3.UseBestLogin("*****@*****.**", "sopabru2011"); foreach (string uid in pop3.GetAll()) { IMail email = new MailBuilder() .CreateFromEml(pop3.GetMessageByUID(uid)); Console.WriteLine("==================================================="); Console.WriteLine(email.Subject); Console.WriteLine(email.Text); foreach (MimeData mime in email.Attachments) { mime.Save(@"C:\AdmToSii\file\libroCompra\proveedores\" + mime.SafeFileName); } Console.WriteLine("==================================================="); } pop3.Close(); } }
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 void AutomatedSmtpResponses(string smtp, string user, string pwd, int port, string toAddress, string toName) { try { for (int i = 0; i < Pop3?.Count; i++) { MimeMessage message = Pop3.GetMessage(i); if (message != null) { string[] words = GetPop3EmailWords(ref message); if (words?.Length > 0) { SendResponses(words, smtp, user, pwd, port, toAddress, toName); } } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
private void CheckEmail(object sender, System.Timers.ElapsedEventArgs args) { try { m_pop3 = new Pop3(); m_pop3.Connect(m_strServer, m_strLogin, m_strPassword); ArrayList list = m_pop3.List(); foreach (Pop3Message msg in list) { Pop3Message msg2 = m_pop3.Retrieve(msg); m_pop3.Delete(msg); _OnMessageReceived(msg2.From, msg2.Subject, false); } m_pop3.Disconnect(); } catch (Pop3Exception e) { _OnError(this, e.Message); return; } }
public void BaixarPop3() { using (Pop3 pop3 = new Pop3()) { //pop3.Connect("host sem SSL"); pop3.ConnectSSL(this.hostPop3); pop3.UseBestLogin(this.MeuEmaail, this.MinhaSenha); foreach (string uid in pop3.GetAll()) { IMail email = new MailBuilder() .CreateFromEml(pop3.GetMessageByUID(uid)); Console.WriteLine(email.Subject); // salva anexo no disco foreach (MimeData mime in email.Attachments) { mime.Save(string.Concat(this.PathAnexo, mime.SafeFileName)); } } pop3.Close(); } }
internal int Pop3Check() { try { var pop3Settings = new Pop3Settings(); var obj = new Pop3(); obj.Connect(pop3Settings.Host, pop3Settings.Username, pop3Settings.Password, pop3Settings.Port); string KeyWord = Helpers.Xml.AppConfigQuery("jaNET/System/Comm/MailKeyword").Item(0).InnerText; foreach (Pop3Message msg in obj.List()) { Pop3Message msg2 = obj.Retrieve(msg); /*Console.WriteLine("Message {0}: {1}", msg2.number, msg2.message);*/ if (msg2.Message.Contains("<" + KeyWord + ">")) { //If a command found to mail subject Match Command = Regex.Match(msg2.Message.Replace("\r\n", " "), @"(<" + KeyWord + ">)(.*?)(?=</" + KeyWord + ">)"); Command.ToString().ToLower().Replace("<" + KeyWord + ">", string.Empty).Parse(); obj.Delete(msg2); } else { //For Future Use /*Match From = Regex.Match(msg2.message, @"(?<=From: )(.*?)(?= <)"); Match Subject = Regex.Match(msg2.message, @"(?<=Subject: )(.*?)(?=\\r\\nDate: )"); //(?<=Subject:</B> )(.*?)(?=</)"); MailList.Add("From " + From.ToString() + ", Subject " + Subject.ToString());*/ //From pattern (?<=From: \\\")(.*?)(?=\\\") //Subject pattern (?<=Subject: )(.*?)(?=\\r) } } obj.Disconnect(); return obj.List().Count; } catch { return 0; } }
public POP3Manager() { this.pop = new Pop3(); }
static void Main(string[] args) { string[] arg; int flag = 0; arg = System.Environment.GetCommandLineArgs(); string path = @"e:\!email-mikrotik\"; for (int i = 0; i < arg.Length; i++) { if (arg[i] == "/dir") { if (!String.IsNullOrEmpty(arg[i + 1])) { path = arg[i + 1]; } } if (arg[i] == "-debug") { flag = 1; } if (arg[i] == "/?") { Console.WriteLine(""); Console.WriteLine("Использование: mail2dirr.exe /dir \"папка для вложений\" [-debug] "); return; } } //string path_base = @"e:\!email-mikrotik\"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (path.Substring(path.Length - 1) != @"\") { path += @"\"; } using (Pop3 pop3 = new Pop3()) { try { pop3.Connect("pop.i.ua"); // or ConnectSSL for SSL pop3.UseBestLogin("*****@*****.**", "dtnjxrfcbhtyb500"); foreach (string uid in pop3.GetAll()) { IMail email = new MailBuilder() .CreateFromEml(pop3.GetMessageByUID(uid)); //бесплатная библиотека мусорит сабжект письма string filenam; filenam = @email.Text.Replace("/", "-"); filenam = email.Text.Replace("\r\n", ""); // email.Save(@"e:\1111qa"); foreach (MimeData mime in email.Attachments) { mime.Save(path + mime.SafeFileName); } } //удаляем сообщения с сервера foreach (string uid in pop3.GetAll()) { pop3.DeleteMessageByUID(uid); } pop3.Close(); } catch (Exception e) { if (flag != 0) { MessageBox((IntPtr)0, e.ToString(), "mail_UDProgram_message", 0); } //path += "ok.ok"; if (!File.Exists(path)) File.Create(path); } } //ставим знак окончания приема писем path += "ok.ok"; if (!File.Exists(path)) { File.Create(path); } }
/// <summary> /// 重要度取得 /// </summary> /// <param name="header">ヘッダ</param> /// <returns>重要度(urgent/normal/non-urgent)</returns> public static string Parse(string header) { string _priority = "normal"; string priority = ""; var pop = new Pop3(); // ヘッダにX-Priorityがあるとき if (header.Contains("X-Priority:")) { priority = pop.GetHeaderField("X-Priority:", header); if (priority == "1" || priority == "2") { _priority = Urgent; } else if (priority == "3") { _priority = Normal; } else if (priority == "4" || priority == "5") { _priority = NonUrgent; } } else if (header.Contains("X-MsMail-Priotiry:")) { priority = pop.GetHeaderField("X-MsMail-Priotiry:", header); if (priority.ToLower() == "High") { _priority = Urgent; } else if (priority.ToLower() == "Normal") { _priority = Normal; } else if (priority.ToLower() == "low") { _priority = NonUrgent; } } else if (header.Contains("Importance:")) { priority = pop.GetHeaderField("Importance:", header); if (priority.ToLower() == "high") { _priority = Urgent; } else if (priority.ToLower() == "normal") { _priority = Normal; } else if (priority.ToLower() == "low") { _priority = NonUrgent; } } else if (header.Contains("Priority:")) { priority = pop.GetHeaderField("Priority:", header); // 重要度の文字列の長さが0以上のときは取得した重要度を入れる if (priority.Length > 0) { _priority = priority; } } return(_priority); }
protected override void Poll() { bool emailDownloaded = false; Exception error = null; try { PollBegin(); using (Pop3 pop3 = new Pop3()) { switch (_sslType) { case SSLType.None: pop3.Connect(_host, _port); break; case SSLType.SSL: pop3.ConnectSSL(_host, _port); break; case SSLType.TLS: pop3.Connect(_host, _port); pop3.STLS(); break; } pop3.UseBestLogin(_username, _password); List <string> serverUids = pop3.GetAll(); MessageStoreCollection localMessageStore = MessageStoreManager.LoadLocalMessageStore(_username, _host); if (localMessageStore != null) { MessageStoreManager.RemoveMessagesNoLongerOnServer(ref localMessageStore, serverUids); List <string> uidsToCheck = MessageStoreManager.GetMessagesToCheck(localMessageStore, serverUids); foreach (string uid in uidsToCheck) { //string fileName; byte[] eml = pop3.GetMessageByUID(uid); IMail email = new MailBuilder().CreateFromEml(eml); //SpoolEmlViaDisk(pop3.GetMessageByUID(uid), out fileName); MessageStoreMessage theMessage = new MessageStoreMessage(uid); if (ProcessEmailAttachments(email) > 0) { emailDownloaded = true; //Only populate the extra data for game emails if (email.From.Count > 0) { theMessage.From = email.From[0].Address; } theMessage.Subject = email.Subject; if (email.Date.HasValue) { theMessage.Date = email.Date.Value.ToString(); theMessage.DateTicks = email.Date.Value.Ticks.ToString(); } //In case the email doesn't come down with a good date if (string.IsNullOrEmpty(theMessage.Date)) { DateTime stamp = DateTime.Now; theMessage.Date = stamp.ToString(); theMessage.DateTicks = stamp.Ticks.ToString(); } theMessage.FileName = GetAttachmentsString(email); } localMessageStore.Messages.Add(theMessage); //ClearSpooledEml(fileName); } } else { //New message store, add all currently on server localMessageStore = new MessageStoreCollection(serverUids); } MessageStoreManager.SaveLocalMessageStore(_username, _host, localMessageStore); localMessageStore.Dispose(); localMessageStore = null; pop3.Close(); } } catch (Exception ex) { error = ex; Trace.TraceError(ex.ToString()); Trace.Flush(); } finally { PollEnd(emailDownloaded, error); } }
//Receives messages from the Mailbox. Note that the state parameter is ignored; we're already //carrying our state in the AsyncState property of the base class. However, Receive() has to //take a single parameter of type Object in order to be a valid WaitCallback delegate. private void doReceive( object state ) { Pop3 pop3 = null; bool bCaughtException = false; //This part does the work of connecting to the POP3 account, logging in, and //checking for new messages. If any messages were found, they will be downloaded //and stored in this.Messages try { Mailbox box = this.AsyncState as Mailbox; string server = box.Options.MailServer; string username = box.Address; string password = box.Options.MailServerPassword; pop3 = new Pop3( ); pop3.User = username; pop3.Password = password; pop3.Connect( server ); if ( pop3.HasTimeStamp ) pop3.APOPLogin( ); else pop3.Login( ); pop3.GetAccountStat( ); this.Messages = new SimpleMailMessage[ pop3.MessageCount ]; log.Debug(string.Format("pop3 check -- {0} - mail count:{1}", username, pop3.MessageCount)); //If we don't have any messages, go to sleep for a little while and try again. //We'll keep doing this sleep/retry loop until a message shows up. That way, SoapTransport //never has to pay any attention to us until we actually have work for it to do. if ( pop3.MessageCount == 0 ) { pop3.Close( ); pop3 = null; SleepAndRetry( box.Options.RetrySeconds ); return; } for ( int i = 1; i <= pop3.MessageCount; i++ ) { try { string message = pop3.GetMessage( i ); this.Messages[ i - 1 ] = SimpleMailMessage.Parse( message ); } finally { pop3.DeleteMessage( i ); } } } catch ( Exception e ) { //This part's very important. Since we're running on a ThreadPool thread right now, any exceptions //thrown on this thread will be swallowed by the ThreadPool. If an exception happens, we need to //somehow marshal it back to the thread that initiated the async operation and rethrow it there. //Forutnately, the AsyncResult base class lets us do that. We'll catch the exception here and //pass it to Complete(). When the originating thread calls AsyncResult.End() on us, the AsyncResult base //class will rethrow the exception on the right thread so it can be handled by the application. bCaughtException = true; base.Complete( false, e ); } finally { if ( pop3 != null ) pop3.Close( true ); } if ( !bCaughtException ) base.Complete( false ); }
/// <summary> /// Mail-To-Weblog runs in background thread and this is the thread function. /// </summary> public void Run() { IBlogDataService dataService = null; ILoggingDataService loggingService = null; SiteConfig siteConfig = SiteConfig.GetSiteConfig(configPath); loggingService = LoggingDataServiceFactory.GetService(logPath); dataService = BlogDataServiceFactory.GetService(contentPath, loggingService); ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, "MailToWeblog thread spinning up"); loggingService.AddEvent(new EventDataItem(EventCodes.Pop3ServiceStart, "", "")); do { try { // reload on every cycle to get the current settings siteConfig = SiteConfig.GetSiteConfig(configPath); loggingService = LoggingDataServiceFactory.GetService(logPath); dataService = BlogDataServiceFactory.GetService(contentPath, loggingService); if (siteConfig.EnablePop3 && siteConfig.Pop3Server != null && siteConfig.Pop3Server.Length > 0 && siteConfig.Pop3Username != null && siteConfig.Pop3Username.Length > 0) { Pop3 pop3 = new Pop3(); try { pop3.host = siteConfig.Pop3Server; pop3.userName = siteConfig.Pop3Username; pop3.password = siteConfig.Pop3Password; pop3.Connect(); pop3.Login(); pop3.GetAccountStat(); for (int j = pop3.messageCount; j >= 1; j--) { Pop3Message message = pop3.GetMessage(j); string messageFrom; // [email protected] 1-MAR-04 // only delete those messages that are processed bool messageWasProcessed = false; // E-Mail addresses look usually like this: // My Name <*****@*****.**> or simply // [email protected]. This block handles // both variants. Regex getEmail = new Regex(".*\\<(?<email>.*?)\\>.*"); Match matchEmail = getEmail.Match(message.from); if (matchEmail.Success) { messageFrom = matchEmail.Groups["email"].Value; } else { messageFrom = message.from; } // Only if the subject of the message is prefixed (case-sensitive) with // the configured subject prefix, we accept the message if (message.subject.StartsWith(siteConfig.Pop3SubjectPrefix)) { Entry entry = new Entry(); entry.Initialize(); entry.Title = message.subject.Substring(siteConfig.Pop3SubjectPrefix.Length); entry.Categories = ""; entry.Content = ""; entry.Author = messageFrom; //store the email, what we have for now... // Grab the categories. Categories are defined in square brackets // in the subject line. Regex categoriesRegex = new Regex("(?<exp>\\[(?<cat>.*?)\\])"); foreach (Match match in categoriesRegex.Matches(entry.Title)) { entry.Title = entry.Title.Replace(match.Groups["exp"].Value, ""); entry.Categories += match.Groups["cat"].Value + ";"; } entry.Title = entry.Title.Trim(); string categories = ""; string[] splitted = entry.Categories.Split(';'); for (int i = 0; i < splitted.Length; i++) { categories += splitted[i].Trim() + ";"; } entry.Categories = categories.TrimEnd(';'); entry.CreatedUtc = RFC2822Date.Parse(message.date); #region PLain Text // plain text? if (message.contentType.StartsWith("text/plain")) { entry.Content += message.body; } #endregion #region Just HTML // Luke Latimer 16-FEB-2004 ([email protected]) // HTML only emails were not appearing else if (message.contentType.StartsWith("text/html")) { string messageText = ""; // Note the email may still be encoded //messageText = QuotedCoding.DecodeOne(message.charset, "Q", message.body); messageText = message.body; // Strip the <body> out of the message (using code from below) Regex bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline); Match match = bodyExtractor.Match(messageText); if (match != null && match.Success && match.Groups["content"] != null) { entry.Content += match.Groups["content"].Value; } else { entry.Content += messageText; } } #endregion // HTML/Text with attachments ? else if ( message.contentType.StartsWith("multipart/alternative") || message.contentType.StartsWith("multipart/related") || message.contentType.StartsWith("multipart/mixed")) { Hashtable embeddedFiles = new Hashtable(); ArrayList attachedFiles = new ArrayList(); foreach (Attachment attachment in message.attachments) { // just plain text? if (attachment.contentType.StartsWith("text/plain")) { entry.Content += StringOperations.GetString(attachment.data); } // Luke Latimer 16-FEB-2004 ([email protected]) // Allow for html-only attachments else if (attachment.contentType.StartsWith("text/html")) { // Strip the <body> out of the message (using code from below) Regex bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline); string htmlString = StringOperations.GetString(attachment.data); Match match = bodyExtractor.Match(htmlString); //NOTE: We will BLOW AWAY any previous content in this case. // This is because most mail clients like Outlook include // plain, then HTML. We will grab plain, then blow it away if // HTML is included later. if (match != null && match.Success && match.Groups["content"] != null) { entry.Content = match.Groups["content"].Value; } else { entry.Content = htmlString; } } // or alternative text ? else if (attachment.contentType.StartsWith("multipart/alternative")) { bool contentSet = false; string textContent = null; foreach (Attachment inner_attachment in attachment.attachments) { // we prefer HTML if (inner_attachment.contentType.StartsWith("text/plain")) { textContent = StringOperations.GetString(inner_attachment.data); } else if (inner_attachment.contentType.StartsWith("text/html")) { Regex bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline); string htmlString = StringOperations.GetString(inner_attachment.data); Match match = bodyExtractor.Match(htmlString); if (match != null && match.Success && match.Groups["content"] != null) { entry.Content += match.Groups["content"].Value; } else { entry.Content += htmlString; } contentSet = true; } } if (!contentSet) { entry.Content += textContent; } } // or text with embeddedFiles (in a mixed message only) else if ((message.contentType.StartsWith("multipart/mixed") || message.contentType.StartsWith("multipart/alternative")) && attachment.contentType.StartsWith("multipart/related")) { foreach (Attachment inner_attachment in attachment.attachments) { // just plain text? if (inner_attachment.contentType.StartsWith("text/plain")) { entry.Content += StringOperations.GetString(inner_attachment.data); } else if (inner_attachment.contentType.StartsWith("text/html")) { Regex bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline); string htmlString = StringOperations.GetString(inner_attachment.data); Match match = bodyExtractor.Match(htmlString); if (match != null && match.Success && match.Groups["content"] != null) { entry.Content += match.Groups["content"].Value; } else { entry.Content += htmlString; } } // or alternative text ? else if (inner_attachment.contentType.StartsWith("multipart/alternative")) { bool contentSet = false; string textContent = null; foreach (Attachment inner_inner_attachment in inner_attachment.attachments) { // we prefer HTML if (inner_inner_attachment.contentType.StartsWith("text/plain")) { textContent = StringOperations.GetString(inner_inner_attachment.data); } else if (inner_inner_attachment.contentType.StartsWith("text/html")) { Regex bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline); string htmlString = StringOperations.GetString(inner_inner_attachment.data); Match match = bodyExtractor.Match(htmlString); if (match != null && match.Success && match.Groups["content"] != null) { entry.Content += match.Groups["content"].Value; } else { entry.Content += htmlString; } contentSet = true; } } if (!contentSet) { entry.Content += textContent; } } // any other inner_attachment else if (inner_attachment.data != null && inner_attachment.fileName != null && inner_attachment.fileName.Length > 0) { if (inner_attachment.contentID.Length > 0) { embeddedFiles.Add(inner_attachment.contentID, StoreAttachment(inner_attachment, binariesPath)); } else { attachedFiles.Add(StoreAttachment(inner_attachment, binariesPath)); } } } } // any other attachment else if (attachment.data != null && attachment.fileName != null && attachment.fileName.Length > 0) { if (attachment.contentID.Length > 0 && message.contentType.StartsWith("multipart/related")) { embeddedFiles.Add(attachment.contentID, StoreAttachment(attachment, binariesPath)); } else { attachedFiles.Add(StoreAttachment(attachment, binariesPath)); } } } // check for orphaned embeddings string[] embeddedKeys = new string[embeddedFiles.Keys.Count]; embeddedFiles.Keys.CopyTo(embeddedKeys, 0); foreach (string key in embeddedKeys) { if (entry.Content.IndexOf("cid:" + key.Trim('<', '>')) == -1) { object file = embeddedFiles[key]; embeddedFiles.Remove(key); attachedFiles.Add(file); } } // now fix up the URIs if (siteConfig.Pop3InlineAttachedPictures) { foreach (string fileName in attachedFiles) { string fileNameU = fileName.ToUpper(); if (fileNameU.EndsWith(".JPG") || fileNameU.EndsWith(".JPEG") || fileNameU.EndsWith(".GIF") || fileNameU.EndsWith(".PNG") || fileNameU.EndsWith(".BMP")) { bool scalingSucceeded = false; if (siteConfig.Pop3InlinedAttachedPicturesThumbHeight > 0) { try { string absoluteFileName = Path.Combine(binariesPath, fileName); string thumbBaseFileName = Path.GetFileNameWithoutExtension(fileName) + "-thumb.dasblog.JPG"; string thumbFileName = Path.Combine(binariesPath, thumbBaseFileName); Bitmap sourceBmp = new Bitmap(absoluteFileName); if (sourceBmp.Height > siteConfig.Pop3InlinedAttachedPicturesThumbHeight) { Bitmap targetBmp = new Bitmap(sourceBmp, new Size( Convert.ToInt32(Math.Round((((double)sourceBmp.Width) * (((double)siteConfig.Pop3InlinedAttachedPicturesThumbHeight) / ((double)sourceBmp.Height))), 0)), siteConfig.Pop3InlinedAttachedPicturesThumbHeight)); ImageCodecInfo codecInfo = GetEncoderInfo("image/jpeg"); Encoder encoder = Encoder.Quality; EncoderParameters encoderParams = new EncoderParameters(1); long compression = 75; EncoderParameter encoderParam = new EncoderParameter(encoder, compression); encoderParams.Param[0] = encoderParam; targetBmp.Save(thumbFileName, codecInfo, encoderParams); string absoluteUri = new Uri(binariesBaseUri, fileName).AbsoluteUri; string absoluteThumbUri = new Uri(binariesBaseUri, thumbBaseFileName).AbsoluteUri; entry.Content += String.Format("<div class=\"inlinedMailPictureBox\"><a href=\"{0}\"><img border=\"0\" class=\"inlinedMailPicture\" src=\"{2}\"></a><br /><a class=\"inlinedMailPictureLink\" href=\"{0}\">{1}</a></div>", absoluteUri, fileName, absoluteThumbUri); scalingSucceeded = true; } } catch { } } if (!scalingSucceeded) { string absoluteUri = new Uri(binariesBaseUri, fileName).AbsoluteUri; entry.Content += String.Format("<div class=\"inlinedMailPictureBox\"><img class=\"inlinedMailPicture\" src=\"{0}\"><br /><a class=\"inlinedMailPictureLink\" href=\"{0}\">{1}</a></div>", absoluteUri, fileName); } } } } if (attachedFiles.Count > 0) { entry.Content += "<p>"; } foreach (string fileName in attachedFiles) { string fileNameU = fileName.ToUpper(); if (!siteConfig.Pop3InlineAttachedPictures || (!fileNameU.EndsWith(".JPG") && !fileNameU.EndsWith(".JPEG") && !fileNameU.EndsWith(".GIF") && !fileNameU.EndsWith(".PNG") && !fileNameU.EndsWith(".BMP"))) { string absoluteUri = new Uri(binariesBaseUri, fileName).AbsoluteUri; entry.Content += String.Format("Download: <a href=\"{0}\">{1}</a><br />", absoluteUri, fileName); } } if (attachedFiles.Count > 0) { entry.Content += "</p>"; } foreach (string key in embeddedFiles.Keys) { entry.Content = entry.Content.Replace("cid:" + key.Trim('<', '>'), new Uri(binariesBaseUri, (string)embeddedFiles[key]).AbsoluteUri); } } loggingService.AddEvent( new EventDataItem( EventCodes.Pop3EntryReceived, entry.Title, SiteUtilities.GetPermaLinkUrl(siteConfig, entry.EntryId), messageFrom)); SiteUtilities.SaveEntry(entry, siteConfig, loggingService, dataService); ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, String.Format("Message stored. From: {0}, Title: {1} as entry {2}", messageFrom, entry.Title, entry.EntryId)); // give the XSS upstreamer a hint that things have changed // XSSUpstreamer.TriggerUpstreaming(); // [email protected] (01-MAR-04) messageWasProcessed = true; } else { // [email protected] (01-MAR-04) // logging every ignored email is apt // to fill up the event page very quickly // especially if only processed emails are // being deleted if (siteConfig.Pop3LogIgnoredEmails) { loggingService.AddEvent( new EventDataItem( EventCodes.Pop3EntryIgnored, message.subject, null, messageFrom)); } } // [email protected] (01-MAR-04) if (siteConfig.Pop3DeleteAllMessages || messageWasProcessed) { if (!messageWasProcessed) { loggingService.AddEvent( new EventDataItem( EventCodes.Pop3EntryDiscarded, message.subject, null, messageFrom)); } pop3.DeleteMessage(j); } } } catch (Exception e) { ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e); loggingService.AddEvent( new EventDataItem( EventCodes.Pop3ServerError, e.ToString().Replace("\n", "<br />"), null, null)); } finally { pop3.Close(); } } Thread.Sleep(TimeSpan.FromSeconds(siteConfig.Pop3Interval)); } catch (ThreadAbortException abortException) { ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, abortException); loggingService.AddEvent(new EventDataItem(EventCodes.Pop3ServiceShutdown, "", "")); break; } catch (Exception e) { // if the siteConfig can't be read, stay running regardless // default wait time is 4 minutes in that case Thread.Sleep(TimeSpan.FromSeconds(240)); ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e); } }while (true); ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, "MailToWeblog thread terminating"); loggingService.AddEvent(new EventDataItem(EventCodes.Pop3ServiceShutdown, "", "")); }
public static Guid FindTargetTrackerKey(Pop3.RxMailMessage mm) { Guid gTARGET_TRACKER_KEY = Sql.ToGuid(mm.Headers["x-splendidcrm-id"]); if ( Sql.IsEmptyGuid(gTARGET_TRACKER_KEY) ) { // 01/13/2008 Paul. Now look for a RemoveMe tracker, or any of the other expected trackers. if ( mm.Body != null ) { foreach ( string sTracker in arrTrackers ) { int nStartTracker = mm.Body.IndexOf(sTracker); if ( nStartTracker > 0 ) { nStartTracker += sTracker.Length; gTARGET_TRACKER_KEY = Sql.ToGuid(mm.Body.Substring(nStartTracker, 36)); if ( !Sql.IsEmptyGuid(gTARGET_TRACKER_KEY) ) return gTARGET_TRACKER_KEY; } } } foreach ( AlternateView vw in mm.AlternateViews ) { if ( vw.TransferEncoding == TransferEncoding.SevenBit || vw.TransferEncoding == TransferEncoding.Base64 ) { Encoding enc = new System.Text.ASCIIEncoding(); switch ( vw.ContentType.CharSet ) { case "UTF-8" : enc = new System.Text.UTF8Encoding (); break; case "UTF-16": enc = new System.Text.UnicodeEncoding(); break; case "UTF-32": enc = new System.Text.UTF32Encoding (); break; } StreamReader rdr = new StreamReader(vw.ContentStream, enc); string sBody = rdr.ReadToEnd(); foreach ( string sTracker in arrTrackers ) { int nStartTracker = sBody.IndexOf(sTracker); if ( nStartTracker > 0 ) { nStartTracker += sTracker.Length; gTARGET_TRACKER_KEY = Sql.ToGuid(sBody.Substring(nStartTracker, 36)); if ( !Sql.IsEmptyGuid(gTARGET_TRACKER_KEY) ) return gTARGET_TRACKER_KEY; } } } } // 01/20/2008 Paul. In a bounce, the server messages will be stored in entities. foreach ( Pop3.RxMailMessage ent in mm.Entities ) { // text/plain // message/delivery-status // message/rfc822 if ( ent.ContentType.MediaType == "text/plain" || ent.ContentType.MediaType == "message/rfc822" ) { gTARGET_TRACKER_KEY = FindTargetTrackerKey(ent); if ( !Sql.IsEmptyGuid(gTARGET_TRACKER_KEY) ) return gTARGET_TRACKER_KEY; } } } return gTARGET_TRACKER_KEY; }
internal async Task <bool> GetPop3BodyonDemand(Email selectedEmail, UserInfo userInfo) { Pop3 pop3 = await ConnectPop3(userInfo); return(await ReadPop3EmailBody(pop3, selectedEmail)); }
/// <summary> /// ReadMail reads the pop3 mailbox /// </summary> public void ReadMail() { Pop3 pop3 = new Pop3(); try { try { pop3.User = Pop3Username; pop3.Password = Pop3Password; pop3.Connect(Pop3Server); if (pop3.HasTimeStamp == true) pop3.Login();//APOPLogin(); else pop3.Login(); pop3.GetAccountStat(); int j = 1; bool messageWasProcessed = false; // Read each message to find out the recipient. This is for the project. for (; j <= pop3.MessageCount; j++) { SimpleMailMessage message = SimpleMailMessage.Parse(pop3.GetMessage(j)); string messageFrom = ""; if (message.From.Count > 0) { MailBox from = message.From[0]; messageFrom = from.Address; } // E-Mail addresses look usually like this: // My Name <*****@*****.**> or simply // [email protected]. This block handles // both variants. // Need to check the TO, CC and BCC message fields for the bugnet email address List<MailBox[]> recipients = new List<MailBox[]>(); recipients.Add((MailBox[])message.To.ToArray()); recipients.Add((MailBox[])message.Cc.ToArray()); recipients.Add((MailBox[])message.Bcc.ToArray()); foreach (MailBox[] toAr in recipients) { foreach (MailBox to in toAr) { string mailbox = to.Address; ProjectMailbox pmbox = ProjectMailbox.GetProjectByMailbox(mailbox); // Only if the mailbox appears in project's mailbox aliases // we accept the message if (pmbox != null) { string binariesBaseUri; string binariesPath; string uploadPath = Project.GetProjectById(pmbox.ProjectId).UploadPath.TrimEnd('/'); //string appPath = HostSetting.GetHostSetting("DefaultUrl"); string appPath = HttpContext.Current.Request.PhysicalApplicationPath; if (!System.IO.Directory.Exists(appPath)) throw new Exception("Upload path does not exist."); if (uploadPath.StartsWith("~")) { binariesPath = uploadPath.Replace("~", appPath.TrimEnd('\\')); if (!System.IO.Directory.Exists(appPath)) throw new Exception("Upload path does not exist."); binariesBaseUri = uploadPath.Replace("~\\", Globals.DefaultUrl).Replace("\\", "/"); } else { binariesPath = string.Concat(appPath, "Uploads\\"); if (!System.IO.Directory.Exists(appPath)) throw new Exception("Upload path does not exist."); binariesBaseUri = string.Concat(Globals.DefaultUrl, "Uploads/"); } Entry entry = new Entry(); entry.Title = message.Subject.Trim(); entry.From = messageFrom; entry.ProjectMailbox = pmbox; entry.Date = message.Date; // plain text? if (message.HtmlDataString.Length == 0) { entry.Content.Append(message.TextDataString); } else { // Strip the <body> out of the message (using code from below) Regex bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline); Match match = bodyExtractor.Match(message.HtmlDataString); if (match != null && match.Success && match.Groups["content"] != null) { entry.Content.Append(match.Groups["content"].Value); } else { entry.Content.Append(message.HtmlDataString); } } Hashtable embeddedFiles = new Hashtable(); ArrayList attachedFiles = new ArrayList(); foreach (MailAttachment attachment in message.Attachments) { if (attachment.Data != null && attachment.FileName != null && attachment.FileName.Length > 0) { string fn = StoreAttachment(attachment, binariesPath); entry.MailAttachments.Add(attachment); entry.AttachmentFileNames.Add(fn); attachedFiles.Add(fn); } } // TODO Should use XSLT templates BGN-1591 if (entry.MailAttachments.Count > 0) { entry.Content.Append("<p>"); for (int i = 0; i < entry.MailAttachments.Count; i++) { MailAttachment attachment = (MailAttachment)entry.MailAttachments[i]; string absoluteUri = string.Concat(binariesBaseUri, entry.AttachmentFileNames[i]); if (Pop3InlineAttachedPictures && attachment.ContentType.MimeType == MimeType.Image) { entry.Content.Append(String.Format("<br><img src=\"{0}\" />", absoluteUri)); } else { entry.Content.Append(String.Format("<br><a href=\"{0}\" />{1}</a>", absoluteUri, attachment.FileName)); } } entry.Content.Append("</p>"); } messageWasProcessed = true; SaveEntry(entry); } else { if (Log.IsWarnEnabled) Log.WarnFormat("Project Mailbox Not Found: {0}", message.To.ToString()); } } } // [email protected] (01-MAR-04) if (Pop3DeleteAllMessages || messageWasProcessed) pop3.DeleteMessage(j); } } catch (Exception ex) { throw ProcessException(ex); } } catch (Exception ex) { throw ProcessException(ex); } finally { try { pop3.Close(); } catch { } } }
/// <summary> /// メールデータをファイルから読み込みます。 /// </summary> public void MailDataLoad() { // 予期せぬエラーの時にメールの本文が分かるようにするための変数 string expSubject = ""; int n = 0; var lockobj = new object(); // スレッドのロックをかける lock (lockobj) { if (File.Exists(Application.StartupPath + @"\Mail.dat")) { try { // ファイルストリームをストリームリーダに関連付ける using (var reader = new StreamReader(Application.StartupPath + @"\Mail.dat", Encoding.UTF8)) { var folders = new MailFolder[] { _receive, _send, _trash }; // GetHederFieldとHeaderプロパティを使うためPop3クラスを作成する using (var pop = new Pop3()) { // データを読み出す foreach (var folder in folders) { try { // メールの件数を読み出す n = Int32.Parse(reader.ReadLine()); } catch (Exception e) { var message = "メール件数とメールデータの数が一致していません。\n件数またはデータレコードをテキストエディタで修正してください。"; MessageBox.Show(message, "Akane Mail", MessageBoxButtons.OK, MessageBoxIcon.Stop); throw new MailLoadException(message, e); } // メールを取得する for (int j = 0; j < n; j++) { // 送信メールのみ必要な項目 string address = reader.ReadLine(); string subject = reader.ReadLine(); // 予期せぬエラーの時にメッセージボックスに表示する件名 expSubject = subject; // ヘッダを取得する string header = ""; string hd = reader.ReadLine(); // 区切り文字が来るまで文字列を連結する while (hd != "\x03") { header += hd + "\r\n"; hd = reader.ReadLine(); } // 本文を取得する string body = ""; string b = reader.ReadLine(); // エラー文字区切りの時対策 bool err_parse = false; // 区切り文字が来るまで文字列を連結する while (b != "\x03") { // 区切り文字が本文の後ろについてしまったとき if (b.Contains("\x03") && b != "\x03") { // 区切り文字を取り除く err_parse = true; b = b.Replace("\x03", ""); } body += b + "\r\n"; // 区切り文字が検出されたときは区切り文字を取り除いてループから抜ける if (err_parse) { break; } b = reader.ReadLine(); } // 受信・送信日時を取得する string date = reader.ReadLine(); // メールサイズを取得する(送信メールは0byte扱い) string size = reader.ReadLine(); // UIDLを取得する(送信メールは無視) string uidl = reader.ReadLine(); // 添付ファイル名を取得する(受信メールは無視) string attach = reader.ReadLine(); // 既読・未読フラグを取得する bool notReadYet = (reader.ReadLine() == "True"); // CCのアドレスを取得する string cc = reader.ReadLine(); // BCCを取得する(受信メールは無視) string bcc = reader.ReadLine(); // 重要度を取得する string priority = reader.ReadLine(); // 旧ファイルを読み込んでいるとき if (priority != "urgent" && priority != "normal" && priority != "non-urgent") { var message = "Version 1.10以下のファイルを読み込もうとしています。\nメールデータ変換ツールで変換してから読み込んでください。"; MessageBox.Show(message, "Akane Mail", MessageBoxButtons.OK, MessageBoxIcon.Stop); throw new MailLoadException(message); } // 変換フラグを取得する(旧バージョンからのデータ移行) string convert = reader.ReadLine(); // ヘッダーがあった場合はそちらを優先する if (header.Length > 0) { // ヘッダープロパティにファイルから取得したヘッダを格納する pop.Header = header; // アドレスを取得する pop.GetDecodeHeaderField("From:"); address = pop.Field ?? address; // 件名を取得する pop.GetDecodeHeaderField("Subject:"); subject = pop.Field ?? subject; // ヘッダからCCアドレスを取得する pop.GetDecodeHeaderField("Cc:"); cc = pop.Field ?? cc; // ヘッダから重要度を取得する priority = MailPriority.Parse(header); } // メール格納配列に格納する var mail = new Mail(address, header, subject, body, attach, date, size, uidl, notReadYet, convert, cc, bcc, priority); folder.Add(mail); } } } } } catch (MailLoadException) { throw; } catch (Exception exp) { MessageBox.Show("予期しないエラーが発生しました。\n" + "件名:" + expSubject + "\n" + "エラー詳細 : \n" + exp.Message, "Akane Mail", MessageBoxButtons.OK, MessageBoxIcon.Stop); throw new MailLoadException("予期しないエラーが発生しました", exp); } } } }
/// <summary> /// Retrieves the DNS query result and displays it. /// </summary> protected override async void OnResume() { base.OnResume(); string server = Intent.GetStringExtra("server"); int port = Intent.GetIntExtra("port", 110); SecurityMode mode = (SecurityMode)Intent.GetIntExtra("security", 0); string username = Intent.GetStringExtra("username"); string password = Intent.GetStringExtra("password"); // switch to 'show output' layout SetContentView(Resource.Layout.Progress); var lblDesc = (TextView)FindViewById(Resource.Id.lblDescription); lblDesc.Text = string.Format("Connecting to POP3 server {0}:{1}...", server, port); Pop3 client = null; try { client = new Pop3(); await client.ConnectAsync(server, port, mode); } catch (Exception ex) { HandleException(ex, "Error occurred while connecting to the server. ", true); return; } if (!string.IsNullOrEmpty(username)) { try { await client.AuthenticateAsync(username, password); } catch (Exception ex) { HandleException(ex, "Error occurred while authenticating the user. ", true); return; } } StringBuilder output = new StringBuilder(); try { Pop3MailboxStat stat = await client.GetMailboxStatAsync(); output.AppendFormat("There are {0} message(s). Total size: {1} bytes.\n", stat.MessageCount, stat.Size); } catch (Exception ex) { HandleException(ex, "Error while obtaining mailbox information. ", true); return; } // switch to 'show output' layout SetContentView(Resource.Layout.Result); // Show output var lblResult = (TextView)FindViewById(Resource.Id.lblResult); lblResult.Text = output.ToString(); }
public static void ImportInboundEmail(HttpApplicationState Application, IDbConnection con, Pop3.RxMailMessage mm, Guid gMAILBOX_ID, string sINTENT, Guid gGROUP_ID) { using ( IDbTransaction trn = con.BeginTransaction() ) { try { string sEMAIL_TYPE = "inbound"; string sSTATUS = "unread"; StringBuilder sbTO_ADDRS = new StringBuilder(); StringBuilder sbTO_ADDRS_NAMES = new StringBuilder(); StringBuilder sbTO_ADDRS_EMAILS = new StringBuilder(); if ( mm.To != null ) { foreach ( MailAddress addr in mm.To ) { // 01/13/2008 Paul. SugarCRM uses commas, but we prefer semicolons. sbTO_ADDRS.Append((sbTO_ADDRS.Length > 0) ? "; " : String.Empty); sbTO_ADDRS.Append(addr.ToString()); sbTO_ADDRS_NAMES.Append((sbTO_ADDRS_NAMES.Length > 0) ? "; " : String.Empty); sbTO_ADDRS_NAMES.Append(!Sql.IsEmptyString(addr.DisplayName) ? addr.DisplayName : addr.Address); sbTO_ADDRS_EMAILS.Append((sbTO_ADDRS_EMAILS.Length > 0) ? "; " : String.Empty); sbTO_ADDRS_EMAILS.Append(addr.Address); } } StringBuilder sbCC_ADDRS = new StringBuilder(); StringBuilder sbCC_ADDRS_NAMES = new StringBuilder(); StringBuilder sbCC_ADDRS_EMAILS = new StringBuilder(); if ( mm.CC != null ) { foreach ( MailAddress addr in mm.CC ) { // 01/13/2008 Paul. SugarCRM uses commas, but we prefer semicolons. sbCC_ADDRS.Append((sbCC_ADDRS.Length > 0) ? "; " : String.Empty); sbCC_ADDRS.Append(addr.ToString()); sbCC_ADDRS_NAMES.Append((sbCC_ADDRS_NAMES.Length > 0) ? "; " : String.Empty); sbCC_ADDRS_NAMES.Append(!Sql.IsEmptyString(addr.DisplayName) ? addr.DisplayName : addr.Address); sbCC_ADDRS_EMAILS.Append((sbCC_ADDRS_EMAILS.Length > 0) ? "; " : String.Empty); sbCC_ADDRS_EMAILS.Append(addr.Address); } } StringBuilder sbBCC_ADDRS = new StringBuilder(); StringBuilder sbBCC_ADDRS_NAMES = new StringBuilder(); StringBuilder sbBCC_ADDRS_EMAILS = new StringBuilder(); if ( mm.Bcc != null ) { foreach ( MailAddress addr in mm.Bcc ) { // 01/13/2008 Paul. SugarCRM uses commas, but we prefer semicolons. sbBCC_ADDRS.Append((sbBCC_ADDRS.Length > 0) ? "; " : String.Empty); sbBCC_ADDRS.Append(addr.ToString()); sbBCC_ADDRS_NAMES.Append((sbBCC_ADDRS_NAMES.Length > 0) ? "; " : String.Empty); sbBCC_ADDRS_NAMES.Append(!Sql.IsEmptyString(addr.DisplayName) ? addr.DisplayName : addr.Address); sbBCC_ADDRS_EMAILS.Append((sbBCC_ADDRS_EMAILS.Length > 0) ? "; " : String.Empty); sbBCC_ADDRS_EMAILS.Append(addr.Address); } } Guid gID = Guid.Empty; // 01/13/2008 Paul. First look for our special header. // Our special header will only exist if the email is a bounce. Guid gTARGET_TRACKER_KEY = Guid.Empty; // 01/13/2008 Paul. The header will always be in lower case. gTARGET_TRACKER_KEY = FindTargetTrackerKey(mm); // 01/20/2008 Paul. mm.DeliveredTo can be NULL. // 01/20/2008 Paul. Filter the XSS tags before inserting the email. // 01/23/2008 Paul. DateTime in the email is in universal time. string sSAFE_BODY = EmailUtils.XssFilter(mm.Body, Sql.ToString(Application["CONFIG.email_xss"])); SqlProcs.spEMAILS_InsertInbound ( ref gID , gGROUP_ID , mm.Subject , mm.DeliveryDate.ToLocalTime() , sSAFE_BODY , String.Empty , ((mm.From != null) ? mm.From.Address : String.Empty) , ((mm.From != null) ? mm.From.ToString() : String.Empty) , sbTO_ADDRS.ToString() , sbCC_ADDRS.ToString() , sbBCC_ADDRS.ToString() , sbTO_ADDRS_NAMES .ToString() , sbTO_ADDRS_EMAILS .ToString() , sbCC_ADDRS_NAMES .ToString() , sbCC_ADDRS_EMAILS .ToString() , sbBCC_ADDRS_NAMES .ToString() , sbBCC_ADDRS_EMAILS.ToString() , sEMAIL_TYPE , sSTATUS , mm.MessageId + ((mm.DeliveredTo != null && mm.DeliveredTo.Address != null) ? mm.DeliveredTo.Address : String.Empty) , ((mm.ReplyTo != null) ? mm.ReplyTo.ToString() : String.Empty) , ((mm.ReplyTo != null) ? mm.ReplyTo.Address : String.Empty) , sINTENT , gMAILBOX_ID , gTARGET_TRACKER_KEY , mm.RawContent , trn ); // 01/20/2008 Paul. In a bounce, the server messages will be stored in entities. foreach ( Pop3.RxMailMessage ent in mm.Entities ) { // text/plain // message/delivery-status // message/rfc822 // 01/20/2008 Paul. Most server status reports will not have a subject, so use the first 300 characters, but take out the CRLF. // 01/21/2008 Paul. Substring will throw an exception if request exceeds length. if ( Sql.IsEmptyString(ent.Subject) && !Sql.IsEmptyString(ent.Body) ) ent.Subject = ent.Body.Substring(0, Math.Min(ent.Body.Length, 300)).Replace("\r\n", " "); Guid gNOTE_ID = Guid.Empty; SqlProcs.spNOTES_Update ( ref gNOTE_ID , mm.ContentType.MediaType + ": " + ent.Subject , "Emails" // Parent Type , gID // Parent ID , Guid.Empty , ent.Body , Guid.Empty // TEAM_ID , trn ); } foreach ( Attachment att in mm.Attachments ) { // 01/13/2008 Paul. We may need to convert the encoding to UTF8. // att.NameEncoding; string sFILENAME = Path.GetFileName (att.Name); string sFILE_EXT = Path.GetExtension(sFILENAME); string sFILE_MIME_TYPE = att.ContentType.MediaType; Guid gNOTE_ID = Guid.Empty; SqlProcs.spNOTES_Update ( ref gNOTE_ID , L10n_Term(Application, "Emails.LBL_EMAIL_ATTACHMENT") + ": " + sFILENAME , "Emails" // Parent Type , gID // Parent ID , Guid.Empty , att.ContentId , Guid.Empty // TEAM_ID , trn ); Guid gNOTE_ATTACHMENT_ID = Guid.Empty; // 01/20/2006 Paul. Must include in transaction SqlProcs.spNOTE_ATTACHMENTS_Insert(ref gNOTE_ATTACHMENT_ID, gNOTE_ID, att.Name, sFILENAME, sFILE_EXT, sFILE_MIME_TYPE, trn); Notes.EditView.LoadFile(gNOTE_ATTACHMENT_ID, att.ContentStream, trn); } trn.Commit(); } catch(Exception ex) { trn.Rollback(); SplendidError.SystemMessage(Application, "Error", new StackTrace(true).GetFrame(0), Utils.ExpandException(ex)); } } }
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); } }
public void Dispose() { if (_disposed) return; _disposed = true; GC.SuppressFinalize(this); _client.Dispose(); _client = null; }
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 ReadMailBox(Configuration config) { log.Info("Check for Mail"); if (!string.IsNullOrEmpty(config.AppSettings.Settings["POPServer"].Value)) { try { if (config.AppSettings.Settings["MailType"].Value == "POP") { using (Pop3 pop3 = new Pop3()) { pop3.ServerCertificateValidate += new ServerCertificateValidateEventHandler(Validate); pop3.ConnectSSL(config.AppSettings.Settings["POPServer"].Value); //pop3.STLS(); pop3.Login(config.AppSettings.Settings["POPMailUser"].Value, config.AppSettings.Settings["POPMailPassword"].Value); foreach (string uid in pop3.GetAll()) { string eml = pop3.GetMessageByUID(uid); IMail mail = new MailBuilder() .CreateFromEml(eml); try { mail.Attachments.ForEach(att => { processAttachment(att, config, mail.Sender.Address); }); pop3.DeleteMessageByUID(uid); } catch (IOException ex) { log.Error(ex.InnerException); } catch (Exception ex) { log.Error(ex); } } pop3.Close(); } } else { #region IMAP Imap imap = new Imap(); //imap.User = ; //imap.Password =; imap.Connect(config.AppSettings.Settings["POPServer"].Value); imap.Login(config.AppSettings.Settings["POPMailUser"].Value, config.AppSettings.Settings["POPMailPassword"].Value); imap.SelectInbox(); List <long> uidList = imap.SearchFlag(Flag.Unseen); log.Debug("Go to process: " + uidList.Count + "mails"); foreach (long uid in uidList) { ISimpleMailMessage imail = new SimpleMailMessageBuilder() .CreateFromEml(imap.GetMessageByUID(uid)); log.Info("Email received: " + imail.From.First().Name); foreach (var att in imail.Attachments) { try { processAttachment(att, config, imail.From.First().Address); } catch (IOException ex) { log.Error(ex.InnerException); imap.FlagMessageByUID(uid, Flag.Flagged); imap.MarkMessageSeenByUID(uid); } catch (Exception ex) { log.Error(ex); imap.FlagMessageByUID(uid, Flag.Flagged); imap.MarkMessageSeenByUID(uid); } } imap.MarkMessageSeenByUID(uid); imap.DeleteMessageByUID(uid); } imap.Close(true); #endregion } log.Info("Mail check complete"); } catch (Exception ex) { log.Error(ex.InnerException); } } else { log.Info("Mail check skipped!"); } }
private bool Dummy(Pop3 pop) { return(true); }
static void Main(string[] args) { Console.WriteLine("Veuillez entrer les éléments de facturation du client :"); string input = Console.ReadLine(); HuffmanTree huffmanTree = new HuffmanTree(); // Construire l'arbre de huffman huffmanTree.Build(input); // Encoder BitArray encoded = huffmanTree.Encode(input); //on retourne le nombre d'octets du message lu au clavier Console.WriteLine(); Console.WriteLine("Votre texte est de " + input.Length + " octets"); //on ouvre une session de connexion sur gmail à travers smtp try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); mail.From = new MailAddress("*****@*****.**"); //expéditeur mail.To.Add("*****@*****.**"); //recepteur mail.Subject = "Informations client"; //objet //ic on affiche d'abord le message compréssé chez l'expéditeur Console.WriteLine(); int cpt = 0; //j'initialise un compte ici pour avoir le nombre de bit à la fin de la compression Console.Write("Compressé: "); foreach (bool bit in encoded) { Console.Write((bit ? 1 : 0) + ""); cpt = cpt + 1; } Console.WriteLine(); Console.WriteLine("le texte compréssé est de " + (cpt / 8 + 1) + " octets"); Console.WriteLine(); Console.WriteLine("En cours d'envoi à " + mail.To + "..."); /*foreach (bool bit in encoded) * { * mail.Body = (bit ? 1 : 0) + ""; * } * Console.WriteLine();*/ string chaine; string message = ""; foreach (bool bit in encoded) { chaine = (bit ? 1 : 0) + ""; message = $"{message}{chaine}"; } mail.Body = message; SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "testisj2019"); SmtpServer.EnableSsl = true; Console.WriteLine(); SmtpServer.Send(mail); Console.WriteLine("Votre mail à été envoyé avec succes!!!");//Message succes } catch (Exception ex) { Console.WriteLine(ex.ToString()); } //cette partie du code permet de lire les mails de l'adresse passée en paramètre try { using (Pop3 pop3 = new Pop3()) { pop3.ConnectSSL("pop.gmail.com"); // or ConnectSSL for SSL pop3.Login("*****@*****.**", "mayelle2010"); List <string> uids = pop3.GetAll(); foreach (string uid in uids) { IMail email = new MailBuilder() .CreateFromEml(pop3.GetMessageByUID(uid)); Console.WriteLine(""); Console.WriteLine(email.Date); Console.WriteLine(email.From); Console.WriteLine(email.Subject); } pop3.Close(); } } catch (Limilabs.Client.ServerException e) { Console.WriteLine(e.ToString()); } }
public Pop3EmailClient() { _pop3 = new Pop3(); }