public void SendingEmail_WithTestTemplate_SendsMailToPickupDirectory() { var email = new { Text = "Texto" }; var emailHeader = new MailHeader(); emailHeader.To = "*****@*****.**"; emailHeader.Subject = "Bienvenido a Encuentrame"; emailHeader.IsHtml = false; EmailService.Send <TestTemplate>(emailHeader, email); DirectoryInfo directory = new DirectoryInfo(EmailSavePath); var files = directory.GetFiles(); Assert.AreEqual(1, files.Length); var mail = GetMessage(files[0]); var text1 = mail.TextBody.TrimEnd(Environment.NewLine.ToCharArray()); text1 = text1.TrimStart(Environment.NewLine.ToCharArray()); Assert.IsTrue(mail.From.Contains(From)); Assert.IsTrue(mail.To.Contains(emailHeader.To)); Assert.AreEqual(email.Text, text1); }
/// <summary> /// Occurs when a mail client message update attempt succeeds. /// </summary> /// <param name="sender">The object that raised the event (MailClient).</param> /// <param name="e">The event data (MessageEventArgs).</param> private async void mailClient_UpdatedMessage(object sender, MessageEventArgs e) { // Get the mail client MailClient mailClient = (MailClient)sender; try { // Get the mail header MailHeader mailHeader = StorageSettings.MailHeaderDictionary[mailClient.AccountSettingsData.EmailAddress][e.Mailbox.FullName].Where(o => o.Uid.Equals(e.Uid, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); // If the mail header is found if (mailHeader != null) { // Remove message from mail header int mailHeaderIndex = StorageSettings.MailHeaderDictionary[mailClient.AccountSettingsData.EmailAddress][e.Mailbox.FullName].IndexOf(mailHeader); StorageSettings.MailHeaderDictionary[mailClient.AccountSettingsData.EmailAddress][e.Mailbox.FullName][mailHeaderIndex].UpdateFlags(e.Message); } // Save await StorageSettings.SaveMailHeaderDictionary(); } catch (Exception ex) { LogFile.Instance.LogError(mailClient.AccountSettingsData.EmailAddress, e.Mailbox.FullName, ex.ToString()); } }
public ActionResult Create(UserModel userModel) { if (ModelState.IsValid) { var userParameters = GetCreateOrEditParameters(userModel); UserCommand.Create(userParameters); AddModelSuccess(Translations.CreateSuccess.FormatWith(TranslationsHelper.Get <User>())); if (!string.IsNullOrEmpty(userModel.Email)) { var welcomeUserEmailModel = new WelcomeUserEmailModel(); welcomeUserEmailModel.Username = userModel.Username; welcomeUserEmailModel.Site = "Encuentrame"; welcomeUserEmailModel.WelcomeInstructions = "A partir de ahora ud puede usar el sistema. Por favor ante cualquier duda o inconveniente comuniquese con el administrador."; var header = new MailHeader(); header.To = userModel.Email; header.Subject = "Bienvenido a Encuentrame"; EmailService.Send <WelcomeUserTemplate>(header, welcomeUserEmailModel); } return(RedirectToAction("Index")); } else { return(View(userModel)); } }
/// <summary> /// Occurs when a mail client message delete attempt succeeds. /// </summary> /// <param name="sender">The object that raised the event (MailClient).</param> /// <param name="e">The event data (MessageEventArgs).</param> private async void mailClient_DeletedMessage(object sender, DeleteMessageEventArgs e) { // Get the mail client MailClient mailClient = (MailClient)sender; try { // Get the mail header MailHeader mailHeader = StorageSettings.MailHeaderDictionary[mailClient.AccountSettingsData.EmailAddress][e.Mailbox.FullName].Where(o => o.Uid == e.MessagePaths.Keys.First()).FirstOrDefault(); // If the mail header is found if (mailHeader != null) { // Remove message from mail header int mailHeaderIndex = StorageSettings.MailHeaderDictionary[mailClient.AccountSettingsData.EmailAddress][e.Mailbox.FullName].IndexOf(mailHeader); StorageSettings.MailHeaderDictionary[mailClient.AccountSettingsData.EmailAddress][e.Mailbox.FullName].Remove(mailHeader); } // Save await StorageSettings.SaveMailHeaderDictionary(); } catch (Exception ex) { LogFile.Instance.LogError(mailClient.AccountSettingsData.EmailAddress, e.Mailbox.FullName, ex.ToString()); } }
private async void MailList_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.AddedItems.Count == 1) { MailHeader o = (MailHeader)e.AddedItems[0]; var res = await MailLogic.GetMail(o); CurrentMail = res; ShowBrowser(); string head = "<head><meta http-equiv='Content-Type' content='text/html;charset=UTF-8'></head>"; if (res.Body.TryGetValue("text/html", out string body)) { Browser.NavigateToString(head + body); } else { Browser.NavigateToString(head + res.Body.Values.First()); } SubjectLabel.Content = $"Subject: {o.Subject}"; FromLabel.Content = $"From: {o.From}"; if (res.Attachments.Count > 0) { AttachmentsBox.IsEnabled = true; AttachmentDownloadButton.IsEnabled = true; AttachmentsBox.ItemsSource = res.Attachments.Keys; AttachmentsBox.SelectedIndex = 0; } else { AttachmentsBox.IsEnabled = false; AttachmentDownloadButton.IsEnabled = false; AttachmentsBox.ItemsSource = null; } } }
public async void SendEmail(string to) { var mailHeader = new MailHeader("X-CUSTOM-HEADER", "Header content"); var headers = new HeaderCollection(); headers.Add(mailHeader); var message = new PostmarkMessage() { To = to, From = "*****@*****.**", TrackOpens = true, Subject = "A complex email", TextBody = "Plain Text Body", HtmlBody = "<html><body><img src=\"cid:embed_name.jpg\"/></body></html>", Tag = "New Year's Email Campaign", Headers = headers }; var imageContent = File.ReadAllBytes("test.jpg"); message.AddAttachment(imageContent, "test.jpg", "image/jpg", "cid:embed_name.jpg"); var client = new PostmarkClient("6cce5c93-a59e-4f32-b37d-c71525956b6b"); var sendResult = await client.SendMessageAsync(message); if (sendResult.Status == PostmarkStatus.Success) /* Handle success */ } {
public static void SendMessage(MailHeader mh, string thissubject, string message) { string from = mh.EmailFromAddress; string to = mh.EmailToAddress; string cc = mh.EmailCcAddress; string bcc = mh.EmailBccAddress; string subject = thissubject; string smtp = mh.EmailSmtpServer; string displayname = mh.EmailSmtpServer; try { MailMessage msg = new MailMessage(); msg.From = new MailAddress(from); if (String.IsNullOrEmpty(to) == false) { string[] addrs = to.Split(';', ','); foreach (string addr in addrs) { msg.To.Add(addr.Trim()); } } if (String.IsNullOrEmpty(cc) == false) { string[] addrs = cc.Split(';', ','); foreach (string addr in addrs) { msg.CC.Add(addr.Trim()); } } if (String.IsNullOrEmpty(bcc) == false) { string[] addrs = bcc.Split(';', ','); foreach (string addr in addrs) { msg.Bcc.Add(addr.Trim()); } } if (mh.Important) { msg.Priority = MailPriority.High; } msg.Subject = subject; msg.Body = message; msg.IsBodyHtml = true; SmtpClient client = new SmtpClient(smtp); client.Port = 587; client.Send(msg); } catch (Exception e) { // Swallow exception Console.WriteLine(e); } }
/// <summary> /// Check if either a MailHeader slot has already been loaded or not. /// WARNING: static checks! No sync against PostOffice is here done! /// </summary> /// <param name="pmh">The item to check</param> /// <returns>It answers to the question. So 'true' means NOT loaded and conversely 'false' is returned if the item is already in.</returns> public bool IsMailHeaderNotLoaded(MailHeader pmh) { bool bret = true; // worst if (pmh == null) { return(bret); } if (pmh.Date == DateTime.MinValue) { return(bret); } if (String.IsNullOrEmpty(pmh.From)) { return(bret); } // PEC does leave it to null! //if ( String.IsNullOrEmpty( pmh.To ) ) // return (bret); // It is loaded. bret = false; return(bret); } // bool IsMailHeaderNotLoaded(...
public static void SendMessage(MailHeader mh, string thissubject, string message) { string from = mh.EmailFromAddress; string to = mh.EmailToAddress; string cc = mh.EmailCcAddress; string bcc = mh.EmailBccAddress; string subject = thissubject; string smtp = mh.EmailSmtpServer; string displayname = mh.EmailSmtpServer; try { MailMessage msg = new MailMessage(); msg.From = new MailAddress(from); if (String.IsNullOrEmpty(to) == false) { string[] addrs = to.Split(';', ','); foreach (string addr in addrs) { msg.To.Add(addr.Trim()); } } if (String.IsNullOrEmpty(cc) == false) { string[] addrs = cc.Split(';', ','); foreach (string addr in addrs) { msg.CC.Add(addr.Trim()); } } if (String.IsNullOrEmpty(bcc) == false) { string[] addrs = bcc.Split(';', ','); foreach (string addr in addrs) { msg.Bcc.Add(addr.Trim()); } } if (mh.Important) msg.Priority = MailPriority.High; msg.Subject = subject; msg.Body = message; msg.IsBodyHtml = true; SmtpClient client = new SmtpClient(smtp); client.Port = 587; client.Send(msg); } catch (Exception e) { // Swallow exception Console.WriteLine(e); } }
public override async Task Classify(MailHeader Mail) { if (Mail.Subject.ToLower().Contains("update")) { Mail.Category = MailCategory.Updates; return; } await Next(Mail); }
public void ImapSslTls_TestConnectionAndAwaitForAnyFirstMessage() { MailHeader mailHeader = TestConnectionAndAwaitAnyFirstMailHeader(MailServerType.Imap, MailServerEncryption.SslTls); if (mailHeader == null) { Assert.Fail(); } }
public void TestHeaders() { string custom1 = "customHeader"; string custom2 = "X-customeHeader2"; string headerValue = "custom value"; MailHeader testHeader = new MailHeader(custom1, headerValue); msg.AddCustomHeader(testHeader); Assertion.Assert(msg.CustomHeaders.Contains(testHeader)); msg.AddCustomHeader(custom2, headerValue); // Assertion.Assert(msg.CustomHeaders.Contains(testHeader)); }
} // List<Message> RetrieveMessages(... /// <summary> /// This method retrieves the mail messages using the IMAP protocol. /// </summary> /// <param name="psMailBoxName"></param> /// <param name="piStart"></param> /// <param name="piCount"></param> /// <returns>A list of Header object(s)</returns> public List <MailHeader> RetrieveHeaders(String psMailBoxName, int piStart, int piCount) { int iCount; List <MailHeader> lstRetVal; do { ErrorMessage = ""; lstRetVal = new List <MailHeader>(); try { Mailbox inbox = this._imap4Client.SelectMailbox(psMailBoxName); Fetch fetch = inbox.Fetch; int messageCount = inbox.MessageCount; iCount = 0; for (int i = piStart; ((i <= messageCount) && (iCount <= piCount)); i++) { MailHeader mailHeader = new MailHeader(); Header header = fetch.HeaderObject(i); String uid = fetch.Uid(i).ToString(); mailHeader.Index = i.ToString(); mailHeader.FillHeader(header); mailHeader.UniqueId = uid; lstRetVal.Add(mailHeader); if (++iCount >= piCount) { break; } } fetch = inbox.Fetch; if (messageCount == this._imap4Client.SelectMailbox(psMailBoxName).MessageCount) { break; } } catch (Exception ex) { log.Error("ImapController Metodo: RetrieveHeaders: ", ex); ErrorMessage = ex.Message; lstRetVal.Clear(); return(lstRetVal); } } while (true); return(lstRetVal); }
} // MailHeader MailHeaderCopy_IndexOf(... // Just to be sure ... // May be semplified ... done. public bool MailHeaderCopy_IsEqual(MailHeader pmh1, MailHeader pmh2) { if (pmh1.UniqueId != pmh2.UniqueId) { return(false); } //if ( pmh1.To != pmh2.To ) // return( false ); //if ( pmh1.From != pmh2.From ) // return( false ); //if ( pmh1.Date != pmh2.Date ) // return( false ); return(true); } // bool MailHeaderCopy_IsEqual(...
private void SendNotification(Notification notification, string subject, dynamic model) { if (notification == null) { return; } var notificationAccess = notification.NotificationAccess; var notificationException = notification.NotificationAccessException; var finalList = new List <BaseUser>(); if (notificationAccess.AllowEveryone) { finalList.AddRange(Users.ToList()); } else if (notificationAccess.Users.Count > 0) { var usersToSend = notificationAccess.Users ?? new List <BaseUser>(); finalList = usersToSend.ToList(); if (notificationException.Users.Count > 0) { finalList = usersToSend.Where(x => !notificationException.Users.Contains(x)).ToList(); } } if (finalList.Count > 0) { foreach (var user in finalList) { var emailHeader = new MailHeader(); emailHeader.To = user.Email; emailHeader.Subject = subject; try { EmailService.Send(emailHeader, notification.TemplateName, model); } catch (Exception e) { Log.Error(string.Format("Error sending email to: {0}", user.Email), e); } } } }
public async Task <Mail> GetMail(MailHeader Mail) { if (CurrentMailBox.FullName != Mail.MailBox.FullName) { await SelectMailBox(Mail.MailBox); } var res = await MailServer.GetMail(Mail.Id); return(new Mail { Body = res.Item1, Attachments = res.Item2, From = Mail.From, Seen = Mail.Seen, Id = Mail.Id, MailBox = CurrentMailBox }); }
/// <summary> /// Method for retrieve the mail headers for POP protocol. /// </summary> /// <returns>The mail headers</returns> public List <MailHeader> RetrieveHeaders() { this.ListMessageInbox.Clear(); int messageCount = this._pop3Client.MessageCount; for (int i = 1; i <= messageCount; i = i + 1) { MailHeader mailHeader = new MailHeader(); Header header = new Header(); header = this._pop3Client.RetrieveHeaderObject(i); mailHeader.Index = i.ToString(); mailHeader.FillHeader(header); this._listHeaderInbox.Add(mailHeader); } return(this.ListHeaderInbox); }
/// <summary> /// Method for retrieve the mail headers for IMAP protocol. /// </summary> /// <param name="mailBox">The mail box</param> /// <returns>The mail headers</returns> public List <MailHeader> RetrieveHeaders(string mailBox) { Mailbox inbox = this._imap4Client.SelectMailbox(mailBox); Fetch fetch = inbox.Fetch; int messageCount = inbox.MessageCount; this._listMessageInbox.Clear(); for (int i = 1; i <= messageCount; i++) { MailHeader mailHeader = new MailHeader(); Header header = fetch.HeaderObject(i); mailHeader.Index = i.ToString(); mailHeader.FillHeader(header); this._listHeaderInbox.Add(mailHeader); } return(this._listHeaderInbox); }
public override Task Classify(MailHeader Mail) { string From; if (Mail.From.Contains('<')) { From = Mail.From.Split('<')[1].Replace(">", ""); } else { From = Mail.From; } if (BankingDomains.Contains(From.Split('@')[1].Trim())) { Mail.Category = MailCategory.Banking; return(Task.CompletedTask); } return(Next(Mail)); }
private string SignHeaders(MailHeader[] headers, MailHeader dkimHeader) { if (headers == null || headers.Length == 0) { throw new ArgumentException("headers"); } var canonicalizer = new DkimCanonicalizer(); var ch = canonicalizer.CanonicalizeHeaders( headers.Union(new[] { dkimHeader }).ToArray(), HeaderCanonicalization); if (SigningAlgorithm != DkimSigningAlgorithm.RSASha256) { throw new NotImplementedException(); } var data = Encoding.GetBytes(ch.TrimEnd()); return(Convert.ToBase64String(RSA.Sign(data, privateKey))); }
public List <MailHeader> GetSentMailList() { string path = Path.Combine(Path.GetTempPath(), Constants.SENT_MAILS_FOLDER); List <MailHeader> ret = null; if (Directory.Exists(path)) { string[] arquivos = Directory.GetFiles(path); ret = new List <MailHeader>(); foreach (string name in arquivos) { Message msg = Parser.ParseMessageFromFile(Path.Combine(path, name)); MailHeader header = new MailHeader(); header.FillHeader(msg, name); ret.Add(header); } } return(ret); }
public async Task TestLoadAllExistingMailHeaders() { try { MailHeader mailHeader = null; var generatedUid = CreateMailHeaderAndInsertIntoDb(); var mailController = CreateMailController(); // Run is not awaiting on purpose. This is only away to add the same time wait for mail header and lead mail header from database. Task.Run(() => { mailController.LoadAllExistingMailHeaders(); }); mailHeader = mailController.MailHeaderStream.Take(1).Timeout(DateTime.Now.AddSeconds(15)).Wait(); if (mailHeader.Uid != generatedUid) { Assert.Fail(); } } catch (Exception e) { Debug.WriteLine(e); Assert.Fail(); } }
} // bool IsMailHeaderNotLoaded(... public int MailHeaderCopy_IndexOf(MailHeader pmh) { int iScan; for (iScan = 1; iScan < aMailHeader_CurrCopy.Length; iScan++) { if (MailHeaderCopy_IsEqual(aMailHeader_CurrCopy[iScan], pmh)) { break; } } if (iScan < aMailHeader_CurrCopy.Length) { return(iScan); } else { return(-1); } } // MailHeader MailHeaderCopy_IndexOf(...
private MailHeader TestConnectionAndAwaitAnyFirstMailHeader(MailServerType serverType, MailServerEncryption serverEncryption) { MailHeader mailHeader = null; var mailController = CreateMailController(); try { mailController.Start(MailServerType.Imap, MailServerEncryption.SslTls, _host, _user, _password); mailHeader = mailController.MailHeaderStream.Take(1).Timeout(DateTime.Now.AddSeconds(15)).Wait(); } catch (Exception e) { Debug.WriteLine(e); mailHeader = null; } finally { mailController.Dispose(); } Debug.WriteLine($"[{mailHeader.Date}] {mailHeader.MailFrom} | Subject: {mailHeader.Subject}"); return(mailHeader); }
public void SendingWelcomeUserEmail_WithTemplateType_SendsMailToPickupDirectory() { var email = new WelcomeUserEmailModel(); email.Username = "******"; email.Site = "Encuentrame"; email.WelcomeInstructions = "A partir de ahora ud puede usar el sistema. Por favor ante cualquier duda o inconveniente comuniquese con el administrador."; var emailHeader = new MailHeader(); emailHeader.To = "*****@*****.**"; emailHeader.Subject = "Bienvenido a Encuentrame"; EmailService.Send <WelcomeUserTemplate>(emailHeader, email); DirectoryInfo directory = new DirectoryInfo(EmailSavePath); var files = directory.GetFiles(); Assert.AreEqual(1, files.Length); var mail = GetMessage(files[0]); Assert.IsTrue(mail.From.Contains(From)); Assert.IsTrue(mail.To.Contains(emailHeader.To)); }
/// <summary> /// Occurs when a mail client message download attempt succeeds. /// </summary> /// <param name="sender">The object that raised the event (MailClient).</param> /// <param name="e">The event data (MessageEventArgs).</param> private async void mailClient_DownloadedMessage(object sender, MessageEventArgs e) { // Get the mail client MailClient mailClient = (MailClient)sender; try { // Create the mail header MailHeader mailHeader = new MailHeader(mailClient.AccountSettingsData.EmailAddress, e.Message.Uid, e.Message, e.Mailbox); // Create the mail header StorageSettings.MailHeaderDictionary.AddOrUpdate(mailClient.AccountSettingsData, e.Mailbox, mailHeader); // Save await StorageSettings.SaveMailHeaderDictionary(); // Get from, subject, body and context string from = (e.Message.From == null ? "(Unknown)" : e.Message.From.DisplayNameAlternate); string subject = e.Message.Subject; string body = e.Message.PlainText; // Only notify todays messages if (e.Message.Date >= DateTime.Today) { string context = null; try { // Create the toast context context = IOUtil.Serialise(new EmailToastNotificationContext(mailClient.AccountSettingsData.EmailAddress, e.Mailbox.FullName, e.Message.Uid)); // Show email notification await Task.Delay(2000); EmailToastNotification.Show(from, subject, body, context); } catch (Exception ex) { LogFile.Instance.LogError(this.GetType().Name, "", ex.ToString()); } } // If this is an unread email if (!mailHeader.IsSeen) { // Update tile if today if (mailHeader.Date >= DateTime.Today) { // Update tile EmailTileNotification.UpdateTile(mailHeader.Uid, from, subject, body); } // Update unread email count int unreadEmailsCount = StorageSettings.MailHeaderDictionary.AllUnreadEmailCount; // Update badge if we haven't reached the limit if (unreadEmailsCount <= 100) { EmailBadgeNotification.UpdateBadge(unreadEmailsCount); } } } catch (Exception ex) { LogFile.Instance.LogError(mailClient.AccountSettingsData.EmailAddress, e.Mailbox.FullName, ex.ToString()); } }
/// <summary> /// First phase: the complete list of the UIds is built. /// </summary> /// <returns></returns> public List <MessageUniqueId> RetrieveUIds() { List <Pop3Client.PopServerUniqueId> lstUId = null; List <MessageUniqueId> lstMUId = null; int iMailHeader; // Create the object if (triggerChanges == null) { triggerChanges = new PostOfficeChangesTrigger(this); } // Restart the container (BUT without requesting reloading (recursive comes here again!) if (MailHeaderSyncCheck(true, false) < 0) { // Problems while connecting ... return(null); } // Get the full UIds list from PostOffice do { switch (InProtoGet()) { case IncomingProtocols.POP3: // Ask server lstUId = this.Pop3.RetrieveUIds(); // Convert from one type to (an)other(s) ... do { lstMUId = new List <MessageUniqueId>(); iMailHeader = 0; foreach (Pop3Client.PopServerUniqueId PSUId in lstUId) { // ------------------------------------------------------------ // iMailHeader++; if (iMailHeader != PSUId.Index) { // Unsynchronized lists (local vs. server) iMailHeader = iMailHeader; } MailHeader mh = new MailHeader(); mh.Index = PSUId.Index.ToString(); mh.UniqueId = PSUId.UniqueId; mh.Date = DateTime.MinValue; // This value flags that the rest is not loaded yet. aMailHeader[iMailHeader] = mh; // ------------------------------------------------------------ // MessageUniqueId muid = new MessageUniqueId(); muid.Ordinal = PSUId.Index; muid.UId = PSUId.UniqueId; lstMUId.Add(muid); // ------------------------------------------------------------ // } // The following line means: if it has changed in the meanwhile, please reload it! } while (triggerChanges.StatisticsUpdate()); break; case IncomingProtocols.IMAP: // doesn't yet exist! lstUId = this.imapController.RetrieveUIds( Constants.MAILBOX ); // Convert from one type to another ... //lstMUId = new List<MessageUniqueId>(); //foreach( Pop3Client.PopServerUniqueId Puid in lstUId ) // { // MessageUniqueId muid = new MessageUniqueId(); // muid.Ordinal = Puid.Index; // muid.UId = Puid.UniqueId; // lstMUId.Add( muid ); // } //TASK: Allineamento log - Ciro ManagedException mEx = new ManagedException("Imap not supported at all!", "ERR_MAIL_0112", string.Empty, string.Empty, null); ErrorLogInfo err = new ErrorLogInfo(mEx); _log.Error(mEx); throw mEx; //throw new ManagedException("Imap not supported at all!", String.Empty, String.Empty, String.Empty, null); break; default: return(null); } } while ((this.Pop3.Pop3Client.IsConnected) && (triggerChanges.StatisticsUpdate() == true)); return(lstMUId); } // List<MailUniqueId> RetrieveUIds()
public List<MailHeader> GetSentMailList() { string path = Path.Combine(Path.GetTempPath(), Constants.SENT_MAILS_FOLDER); List<MailHeader> ret = null; if (Directory.Exists(path)) { string[] arquivos = Directory.GetFiles(path); ret = new List<MailHeader>(); foreach (string name in arquivos) { Message msg = Parser.ParseMessageFromFile(Path.Combine(path, name)); MailHeader header = new MailHeader(); header.FillHeader(msg, name); ret.Add(header); } } return ret; }
///------------------------------------------------------------- /// <summary> /// メール受信 </summary> ///------------------------------------------------------------- private void PopTest() { // メール設定データ if (!dts.メール設定.Any(a => a.ID == global.mailKey)) { return; } var s = dts.メール設定.Single(a => a.ID == global.mailKey); //処理中 _mJob = global.flgOn; //マウスポインタを待機にする this.Cursor = Cursors.WaitCursor; //受信メールカウント int _mCount = 0; //ファイル名連番 int fNumber = 0; //message-ID string _msid; // POPサーバ、ユーザ名、パスワードを設定 string hostname = s.POPサーバー; string username = s.ログイン名; string password = s.パスワード; int popPort = s.POPポート番号; // POP サーバに接続します。 //addListView(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), "POPサーバに接続", Color.Black); PopClient pop = new PopClient(hostname, popPort); //POPサーバへの接続障害時は何もしないで待機状態へ戻る 2011/07/20 if (global.Msglog.StartsWith("ERR")) { //addListView(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), global.Msglog, Color.Red); //非処理中ステータス _mJob = global.flgOff; //マウスポインタを戻す this.Cursor = Cursors.Default; return; } //addListView(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), global.Msglog, Color.Black); // ログインします。 pop.Login(username, password); // POP サーバに溜まっているメールのリストを取得します。 ArrayList list = pop.GetList(); for (int i = 0; i < list.Count; ++i) { // メール本体を取得する string mailtext = pop.GetMail((string)list[i]); // Mail クラスを作成 Mail mail = new Mail(mailtext); //受信対象メールの判定値 int _mTarget = 0; //message-IDを取得 if (mail.Header["Message-ID"].Length > 0) { _msid = MailHeader.Decode(mail.Header["Message-ID"][0]).Replace("Message-ID: ", ""); // 2015/11/24 _msid = _msid.Replace("Message-Id: ", ""); } else { _msid = string.Empty; } // 重複メールは受信しない if (getMessageid(_msid)) { //Content-Typeがあるメール if (mail.Header["Content-Type"].Length > 0) { string fAdd = string.Empty; if (Properties.Settings.Default.checkfromAddress != null) { fAdd = Properties.Settings.Default.checkfromAddress; } // 差出人指定があるときアドレスを調べる if (fAdd != string.Empty) { if (!MailHeader.Decode(mail.Header["From"][0]).Replace("From: ", "").Contains(fAdd)) { continue; } } _mTarget = 1; ////差出人アドレスを調べる //foreach (string add in reAddress) //{ // if (MailHeader.Decode(mail.Header["From"][0]).Replace("From: ", "").IndexOf(add) >= 0) // { // _mTarget = 1; // break; // } //} } } // 受信対象メールのとき以下の処理を実行する if (_mTarget == 1) { // メールデータ mailData md = new mailData(); mailDataInitial(md); //メールデータ初期化 string sStr = string.Empty; // 送信日時を取得 if (mail.Header["Date"].Length > 0) { sStr = MailHeader.Decode(mail.Header["Date"][0]).Replace("Date: ", "").Trim(); //タイムゾーン記号を消去 sStr = sStr.Replace("(JST)", "").Trim(); sStr = sStr.Replace("(UT)", "").Trim(); sStr = sStr.Replace("(EST)", "").Trim(); sStr = sStr.Replace("(CST)", "").Trim(); sStr = sStr.Replace("(MST)", "").Trim(); sStr = sStr.Replace("(PST)", "").Trim(); sStr = sStr.Replace("(EDT)", "").Trim(); sStr = sStr.Replace("(CDT)", "").Trim(); sStr = sStr.Replace("(MDT)", "").Trim(); sStr = sStr.Replace("(PDT)", "").Trim(); sStr = sStr.Replace("(GMT)", "").Trim(); sStr = sStr.Replace("(C)", "").Trim(); sStr = sStr.Replace("(UTC)", "").Trim(); sStr = sStr.Replace("JST", "").Trim(); sStr = sStr.Replace("UT", "").Trim(); sStr = sStr.Replace("EST", "").Trim(); sStr = sStr.Replace("CST", "").Trim(); sStr = sStr.Replace("MST", "").Trim(); sStr = sStr.Replace("PST", "").Trim(); sStr = sStr.Replace("EDT", "").Trim(); sStr = sStr.Replace("CDT", "").Trim(); sStr = sStr.Replace("MDT", "").Trim(); sStr = sStr.Replace("PDT", "").Trim(); sStr = sStr.Replace("GMT", "").Trim(); sStr = sStr.Replace("C", "").Trim(); sStr = sStr.Replace("UTC", "").Trim(); //dg1[0, dg1.Rows.Count - 1].Value = DateTime.Parse(sStr).ToString("yyyy/M/dd HH:mm:ss"); // 世界標準時(RFC2822表記)からDetaTime型に変換 try { string[] expectedFormats = { "ddd, d MMM yyyy HH':'mm':'ss", "ddd, d MMM yyyy HH':'mm':'ss zzz", "d MMM yyyy HH':'mm':'ss", "d MMM yyyy HH':'mm':'ss zzz", "d", "D", "f", "F", "g", "G", "m", "r", "R", "s", "t", "T", "u", "U", "y" }; DateTime myUtcDT3 = System.DateTime.ParseExact(sStr, expectedFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None); md.sendTime = myUtcDT3.ToString("yyyy/MM/dd HH:mm:ss"); } catch (Exception) { md.sendTime = sStr; } } else { sStr = string.Empty; } //差出人 md.fromAddress = MailHeader.Decode(mail.Header["From"][0]).Replace("From: ", ""); md.fromAddress = md.fromAddress.Replace("'", " "); //if (md.fromAddress.IndexOf(Properties.Settings.Default.interFaxAddress) >= 0) //{ // _fromInterFax = 1; //} //else //{ // _fromInterFax = 0; //} //宛先 if (mail.Header["To: "].Length > 0) { md.toAddress = MailHeader.Decode(mail.Header["To: "][0]).Replace("To:", ""); md.toAddress = md.toAddress.Replace("'", " "); } else { md.toAddress = string.Empty; } //if (_fromInterFax == 1) //差出人がinterfaxのとき //{ // md.toAddress = MailHeader.Decode(mail.Header["X-Interfax-InterFAXNumber:"][0]).Replace("X-Interfax-InterFAXNumber: ", ""); // md.toAddress = md.toAddress.Replace("'", " "); //} //else //{ // md.toAddress = MailHeader.Decode(mail.Header["To:"][0]).Replace("To: ", ""); // md.toAddress = md.toAddress.Replace("'", " "); //} //件名 //件名がないとき 2011/06/27 if (mail.Header["Subject"].Length > 0) { md.subject = MailHeader.Decode(mail.Header["Subject"][0]).Replace("Subject: ", ""); md.subject = md.subject.Replace("'", " "); } //マルチパートの判定 int mp = mail.Body.Multiparts.Length; //マルチパート または multipart/alternativeの判断 if (mp == 0) //マルチパートではない { //Content-Type sStr = MailHeader.Decode(mail.Header["Content-Type"][0]).Replace("Content-Type:", "").Trim(); //charset if (sStr.IndexOf("charset=") > -1) { string sCharset = sStr.Substring(sStr.IndexOf("charset=")).Replace("charset=", ""); sCharset = sCharset.Replace(@"""", ""); // 2015/11/21 int cs = sCharset.IndexOf(";"); if (cs > -1) { // 2015/11/21 utf-8; reply-type=originalの「; reply-type=original」部を消去する string cc = sCharset.Substring(cs, sCharset.Length - cs); sCharset = sCharset.Replace(cc, ""); } // メール本文を取得する // Content-Type の charset を参照してデコード if (mail.Header["Content-Transfer-Encoding"].Length > 0) { sStr = MailHeader.Decode(mail.Header["Content-Transfer-Encoding"][0]).Replace("Content-Transfer-Encoding:", "").Trim(); byte[] bytes; if (sStr == "base64" || sStr == "BASE64") { bytes = Convert.FromBase64String(mail.Body.Text); } else { bytes = Encoding.ASCII.GetBytes(mail.Body.Text); } // 2016/02/18 if (sCharset == "cp932") { sCharset = "Shift_JIS"; } string mailbody = Encoding.GetEncoding(sCharset).GetString(bytes); md.message = mailbody.Replace("'", " "); } else { md.message = string.Empty; } } else { md.message = string.Empty; } } else //マルチパートのとき { //本文の確認 2011/06/27 for (int ix = 0; ix < mp; ix++) { //Content-Type を検証する MailMultipart part1 = mail.Body.Multiparts[ix]; //マルチパートの更に中のマルチパート数を取得する 2011/06/27 int mb = part1.Body.Multiparts.Length; //マルチパートの中のマルチパート毎の"Content-Type"を検証する 2011/06/27 for (int n = 0; n < mb; n++) { //Content-Type を検証する MailMultipart p = part1.Body.Multiparts[n]; sStr = MailHeader.Decode(p.Header["Content-Type"][0]).Replace("Content-Type:", "").Trim(); //本文("text/plain")か? 2011/06/27 if (sStr.IndexOf("text/plain") >= 0) { //charset if (sStr.IndexOf("charset=") > -1) { string sCharset = sStr.Substring(sStr.IndexOf("charset=")).Replace("charset=", ""); sCharset = sCharset.Replace(@"""", ""); // 2015/11/21 int cs = sCharset.IndexOf(";"); if (cs > -1) { // 2015/11/21 utf-8; reply-type=originalの「; reply-type=original」部を消去する string cc = sCharset.Substring(cs, sCharset.Length - cs); sCharset = sCharset.Replace(cc, ""); } //エンコード名以降の文字列を削除する int m = sCharset.IndexOf(";"); if (m >= 0) { sCharset = sCharset.Remove(m); } // メール本文を取得する // Content-Type の charset を参照してデコード //Content-Transfer-Encodingを取得する if (mail.Header["Content-Transfer-Encoding"].Length > 0) { sStr = MailHeader.Decode(p.Header["Content-Transfer-Encoding"][0]).Replace("Content-Transfer-Encoding:", "").Trim(); byte[] bytes; if (sStr == "base64" || sStr == "BASE64") { bytes = Convert.FromBase64String(p.Body.Text); } else { bytes = Encoding.ASCII.GetBytes(p.Body.Text); } // 2016/02/18 if (sCharset == "cp932") { sCharset = "Shift_JIS"; } string mailbody = Encoding.GetEncoding(sCharset).GetString(bytes); md.message = mailbody.Replace("'", " "); } else { md.message = string.Empty; } } break; } } } // 添付ファイルの確認 //↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ for (int ix = 1; ix < mp; ix++) { //Content-Type を検証する MailMultipart part2 = mail.Body.Multiparts[ix]; sStr = MailHeader.Decode(part2.Header["Content-Type"][0]).Replace("Content-Type:", "").Trim(); int fType = global.ANYFILE; //添付ファイルがCSVファイルならば保存する if (sStr.Contains("text/csv")) { fType = global.CSVFILE; //Content-Transfer-Encodingを取得する sStr = MailHeader.Decode(part2.Header["Content-Transfer-Encoding"][0]).Replace("Content-Transfer-Encoding:", "").Trim(); if (sStr == "base64") { byte[] bytes = Convert.FromBase64String(part2.Body.Text); string fName; fName = string.Format("{0:0000}", DateTime.Today.Year) + string.Format("{0:00}", DateTime.Today.Month) + string.Format("{0:00}", DateTime.Today.Day) + string.Format("{0:00}", DateTime.Now.Hour) + string.Format("{0:00}", DateTime.Now.Minute) + string.Format("{0:00}", DateTime.Now.Second); fNumber++; //保存フォルダがあるか?なければ作成する(CSVフォルダ) if (!System.IO.Directory.Exists(Properties.Settings.Default.reCsvPath)) { System.IO.Directory.CreateDirectory(Properties.Settings.Default.reCsvPath); } fName = Properties.Settings.Default.reCsvPath + fName + string.Format("{0:000}", fNumber) + ".csv"; using (Stream stm = File.Open(fName, FileMode.Create)) using (BinaryWriter bw = new BinaryWriter(stm)) { bw.Write(bytes); } //添付ファイル名 md.addFilename = fName; } } } } //// 確認用に取得したメールをそのままカレントディレクトリに書き出します。 //using (StreamWriter sw = new StreamWriter(DateTime.Now.ToString("yyyyMMddHHmmssfff") + i.ToString("0000") + ".txt")) //{ // sw.Write(mailtext); //} // メールを POP サーバから取得します。 // ★注意★ // 削除したメールを元に戻すことはできません。 // 本当に削除していい場合は以下のコメントをはずしてください。 //pop.DeleteMail((string)list[i]); // 通信ログ書き込み putMaillog(md); // messageid履歴書き込み messageidUpDate(_msid); _mCount++; } } // 切断する pop.Close(); //非処理中ステータス _mJob = global.JOBOUT; //マウスポインタを戻す this.Cursor = Cursors.Default; // 終了表示 MessageBox.Show(_mCount.ToString() + "件のメールを受信しました。"); }
/// <summary> /// Method for retrieve the mail headers for POP protocol. /// </summary> /// <returns>The mail headers</returns> public List<MailHeader> RetrieveHeaders() { this.ListMessageInbox.Clear(); int messageCount = this._pop3Client.MessageCount; for (int i = 1; i <= messageCount; i = i + 1) { MailHeader mailHeader = new MailHeader(); Header header = new Header(); header = this._pop3Client.RetrieveHeaderObject(i); mailHeader.Index = i.ToString(); mailHeader.FillHeader(header); this._listHeaderInbox.Add(mailHeader); } return this.ListHeaderInbox; }
public override Task Classify(MailHeader Mail) { Mail.Category = MailCategory.Promotion; return(Task.CompletedTask); }
// sends a multipart mail to the server private void SendMultipartMail( MailMessageWrapper msg ) { // generate the boundary between attachments string boundary = MailUtil.GenerateBoundary(); // set the Content-Type header to multipart/mixed string bodyContentType = msg.Header.ContentType; msg.Header.ContentType = System.String.Format( "multipart/mixed;\r\n boundary={0}" , boundary ); // write the header smtp.WriteHeader( msg.Header ); // write the first part text part // before the attachments smtp.WriteBoundary( boundary ); MailHeader partHeader = new MailHeader(); partHeader.ContentType = bodyContentType; smtp.WriteHeader( partHeader ); // FIXME: probably need to use QP or Base64 on everything higher // then 8-bit .. like utf-16 smtp.WriteBytes( msg.BodyEncoding.GetBytes( msg.Body ) ); smtp.WriteBoundary( boundary ); // now start to write the attachments for( int i=0; i< msg.Attachments.Count ; i++ ) { MailAttachment a = (MailAttachment)msg.Attachments[ i ]; FileInfo fileInfo = new FileInfo( a.Filename ); MailHeader aHeader = new MailHeader(); aHeader.ContentType = String.Format (MimeTypes.GetMimeType (fileInfo.Name) + "; name=\"{0}\"",fileInfo.Name); aHeader.ContentDisposition = String.Format( "attachment; filename=\"{0}\"" , fileInfo.Name ); aHeader.ContentTransferEncoding = a.Encoding.ToString(); smtp.WriteHeader( aHeader ); // perform the actual writing of the file. // read from the file stream and write to the tcp stream FileStream ins = fileInfo.OpenRead (); // create an apropriate encoder IAttachmentEncoder encoder; if( a.Encoding == MailEncoding.UUEncode ) { encoder = new UUAttachmentEncoder( 644 , fileInfo.Name ); } else { encoder = new Base64AttachmentEncoder(); } encoder.EncodeStream( ins , smtp.Stream ); ins.Close(); smtp.WriteLine( "" ); // if it is the last attachment write // the final boundary otherwise write // a normal one. if( i < (msg.Attachments.Count - 1) ) { smtp.WriteBoundary( boundary ); } else { smtp.WriteFinalBoundary( boundary ); } } }
public abstract Task Classify(MailHeader Mail);
protected Task Next(MailHeader Mail) { return(NextClassifier.Classify(Mail)); }
/// <summary> /// Method for retrieve the mail headers for IMAP protocol. /// </summary> /// <param name="mailBox">The mail box</param> /// <returns>The mail headers</returns> public List<MailHeader> RetrieveHeaders(string mailBox) { Mailbox inbox = this._imap4Client.SelectMailbox(mailBox); Fetch fetch = inbox.Fetch; int messageCount = inbox.MessageCount; this._listMessageInbox.Clear(); for (int i = 1; i <= messageCount; i++) { MailHeader mailHeader = new MailHeader(); Header header = fetch.HeaderObject(i); mailHeader.Index = i.ToString(); mailHeader.FillHeader(header); this._listHeaderInbox.Add(mailHeader); } return this._listHeaderInbox; }