/// <summary> /// Gets specified folder messages list from IMAP server. /// </summary> /// <param name="folder">IMAP folder which messages to load.</param> private void LoadFolder(string folder) { try { _client.SelectFolder(folder); if (_client.SelectedFolder.MessagesCount == 0) { return; } var seqSet = GetSeqSet(); if (seqSet == null) { throw new ArgumentNullException(nameof(seqSet)); } if (string.IsNullOrWhiteSpace(seqSet)) { return; } AppJournal.Write("EmailImapTransport: LoadFolder: Seq_set = " + GetSeqSet()); _client.Fetch(false, IMAP_t_SeqSet.Parse(GetSeqSet()), new IMAP_t_Fetch_i[] { new IMAP_t_Fetch_i_Envelope(), new IMAP_t_Fetch_i_Flags(), new IMAP_t_Fetch_i_InternalDate(), new IMAP_t_Fetch_i_Rfc822Size(), new IMAP_t_Fetch_i_Uid() }, FetchFolderHandler); _savedSeqNo = _messages.Last().UID + 1; _criteria = SeqSetCriteriaEnum.SaveNo; } catch (Exception ex) { //Debug.WriteLine(ex.Message); AppJournal.Write("EmailImapTransport:LoadFolder: " + ex.Message); } }
public void getMailSendImap(string userName, string psw, string service, bool ssl, int port) { try { IMAP_Client imapc = loginMail(userName, psw, service, ssl, port); var folderlist = imapc.GetFolders(null); imapc.SelectFolder("Éléments envoyés"); //imapc.SelectFolder("INBOX"); var folder = imapc.SelectedFolder; var seqSet = IMAP_t_SeqSet.Parse("1:*"); var items = new IMAP_t_Fetch_i[] { new IMAP_t_Fetch_i_Envelope(), new IMAP_t_Fetch_i_Uid(), new IMAP_t_Fetch_i_Flags(), new IMAP_t_Fetch_i_InternalDate(), new IMAP_t_Fetch_i_Rfc822() }; imapc.Fetch(false, seqSet, items, this.m_pImap_Fetch_MessageItems_UntaggedResponse); System.Threading.Thread.Sleep(500); DataTable dtmail = datalistmail.getInstance().getdtSend(); SqlDataAdapter adapteremailrecu = CreerDataAdapterFormail("MailSend"); dtmail.DefaultView.Sort = "maildateTime DESC"; int tr = adapteremailrecu.Update(dtmail.Select(null, null, DataViewRowState.ModifiedCurrent)); int tr12 = adapteremailrecu.Update(dtmail.Select(null, null, DataViewRowState.Added)); //System.Threading.Thread.Sleep(500); imapc.Disconnect(); } catch (Exception ex) { Console.WriteLine("ErrGetMail:" + ex.Message); } }
public void getEmail(string login, string password) { IMAP_Client client = new IMAP_Client(); client.Connect("imap.yandex.ru", 993, true); client.Login(login, password); client.SelectFolder("INBOX"); IMAP_SequenceSet sequence = new IMAP_SequenceSet(); //sequence.Parse("*:1"); // from first to last IMAP_Client_FetchHandler fetchHandler = new IMAP_Client_FetchHandler(); fetchHandler.NextMessage += new EventHandler(delegate(object s, EventArgs e) { Console.WriteLine("next message"); }); fetchHandler.Envelope += new EventHandler <EventArgs <IMAP_Envelope> >(delegate(object s, EventArgs <IMAP_Envelope> e) { IMAP_Envelope envelope = e.Value; if (envelope.From != null && !String.IsNullOrWhiteSpace(envelope.Subject)) { Console.WriteLine(envelope.Subject); } }); // the best way to find unread emails is to perform server search int[] unseen_ids = client.Search(false, "UTF-8", "unseen"); Console.WriteLine("unseen count: " + unseen_ids.Count().ToString()); // now we need to initiate our sequence of messages to be fetched sequence.Parse(string.Join(",", unseen_ids)); // fetch messages now client.Fetch(false, sequence, new IMAP_Fetch_DataItem[] { new IMAP_Fetch_DataItem_Envelope() }, fetchHandler); // uncomment this line to mark messages as read // client.StoreMessageFlags(false, sequence, IMAP_Flags_SetType.Add, IMAP_MessageFlags.Seen); }
/* * public void marksUnread(IMAP_Client client, IMAP_Client_FetchHandler fetchHandler) * { * IMAP_SequenceSet sequence = new IMAP_SequenceSet(); * //sequence.Parse("*:1"); // from first to last * // the best way to find unread emails is to perform server search * int[] unseen_ids = client.Search(false, "UTF-8", "unseen"); * Console.WriteLine("unseen count: " + unseen_ids.Count().ToString()); * // now we need to initiate our sequence of messages to be fetched * sequence.Parse(string.Join(",", unseen_ids)); * // fetch messages now * client.Fetch(false, sequence, new IMAP_Fetch_DataItem[] { new IMAP_Fetch_DataItem_Envelope() }, fetchHandler); * // uncomment this line to mark messages as read * // client.StoreMessageFlags(false, sequence, IMAP_Flags_SetType.Add, IMAP_MessageFlags.Seen); * * }*/ #region method LoadFolderMessages /// <summary> /// Gets specified folder messages list from IMAP server and adds them to UI. /// </summary> /// <param name="folder">IMAP folder which messages to load.</param> private void LoadFolderMessages(IMAP_Client m_pImap, string folder) { try { m_pImap.SelectFolder(folder); // No messages in folder, skip fetch. if (m_pImap.SelectedFolder.MessagesCount == 0) { return; } // Start fetching. m_pImap.Fetch( false, IMAP_t_SeqSet.Parse("*"), new IMAP_t_Fetch_i[] { new IMAP_t_Fetch_i_Envelope(), new IMAP_t_Fetch_i_Flags(), new IMAP_t_Fetch_i_InternalDate(), new IMAP_t_Fetch_i_Rfc822Size(), new IMAP_t_Fetch_i_Uid() }, m_pImap_Fetch_MessageItems_UntaggedResponse ); } catch (Exception x) { Console.WriteLine(x.ToString()); } }
private void LoadMessage(IMAP_Client m_pImap, string folder) { try {//uid.ToString() m_pImap.SelectFolder(folder); // Start fetching. m_pImap.Fetch( true, IMAP_t_SeqSet.Parse("*"),//последнее письмо должно быть new IMAP_t_Fetch_i[] { new IMAP_t_Fetch_i_Rfc822() }, this.m_pImap_Fetch_Message_UntaggedResponse ); } catch (Exception x) { Console.WriteLine("ЭКСЕПШН" + x.ToString() + "ЗАКОНЧИЛСЯ"); } }
/// <summary> /// Examples: /// 2 -> seq-number (2) /// 2:4 -> seq-range (from 2 - 4) /// 2:* -> seq-range (from 2 to last) /// 2,3,10:* -> sequence-set (seq-number,seq-number,seq-range) /// (2,3, 10 - last) /// </summary> /// <param name="start"></param> /// <param name="end"></param> public void LoadMessages(String start, String end) { Messages.Clear(); if (!_IsConnected) { throw new EMailException { ExceptionType = EMAIL_EXCEPTION_TYPE.NOT_CONNECTED } } ; if (!String.IsNullOrWhiteSpace(_CurrentFolder)) { Client.Fetch( false, IMAP_t_SeqSet.Parse(start + ":" + end), new IMAP_t_Fetch_i[] { new IMAP_t_Fetch_i_Envelope(), new IMAP_t_Fetch_i_Flags(), new IMAP_t_Fetch_i_InternalDate(), new IMAP_t_Fetch_i_Rfc822Size(), new IMAP_t_Fetch_i_Uid() }, (s, e) => { try { IMAP_r_u_Fetch fetchResp = (IMAP_r_u_Fetch)e.Value; string from = ""; if (fetchResp.Envelope.From != null) { for (int i = 0; i < fetchResp.Envelope.From.Length; i++) { // Don't add ; for last item if (i == fetchResp.Envelope.From.Length - 1) { from += fetchResp.Envelope.From[i].ToString(); } else { from += fetchResp.Envelope.From[i].ToString() + ";"; } } } else { from = "<none>"; } string Subject = fetchResp.Envelope.Subject != null ? fetchResp.Envelope.Subject : "<none>"; string Date = fetchResp.InternalDate.Date.ToString("dd.MM.yyyy HH:mm"); string size = ((decimal)(fetchResp.Rfc822Size.Size / (decimal)1000)).ToString("f2") + " kb"; Mail_t_Address[] froms = fetchResp.Envelope.From; string Tag = fetchResp.UID.UID.ToString(); IMAP_Message_Wrapper wr = new IMAP_Message_Wrapper { Client = Client, SequenceNumber = (int)fetchResp.UID.UID, UID = Tag, Date = fetchResp.InternalDate.Date, Size = fetchResp.Rfc822Size.Size, Subject = Subject }; foreach (var item in froms) { if (item is Mail_t_Mailbox) { wr.From.Add(((Mail_t_Mailbox)item).Address); } } //var F = fetchResp.Flags.Flags; //if(!F.Contains("\\Deleted")) _Messages.Add(wr); } catch (Exception exe) { throw new EMailException { ExceptionType = EMAIL_EXCEPTION_TYPE.ERROR_ON_GET_MESSAGE, InnerException = exe }; } } ); if (OnMessagesLoaded != null) { OnMessagesLoaded(this); } } }
//#region 获取当前外网ip地址 //private string GetIP() //{ // string strUrl = "http://www.ip138.com/ip2city.asp"; //获得IP的网址了 // Uri uri = new Uri(strUrl); // WebRequest wr = WebRequest.Create(uri); // Stream s = wr.GetResponse().GetResponseStream(); // StreamReader sr = new StreamReader(s, Encoding.Default); // string all = sr.ReadToEnd(); //读取网站的数据 // int i = all.IndexOf("[") + 1; // string tempip = all.Substring(i, 15); // string ip = tempip.Replace("]", "").Replace(" ", ""); // return ip; //} //#endregion #region 未读邮件信息 private void QueryEmailStatus() { IMAP_Client IMAPServer = new IMAP_Client(); try { //连接邮件服务器通过传入邮件服务器地址和用于IMAP协议的端口号 IMAPServer.Connect(@"imap.exmail.sina.com", 143, false); string currUserCode = UserInfo.GetInstence().UserCode; string emailPassword = string.Empty; //登陆邮箱,前者帐号后者密码 using (var context = new BugTraceEntities(EntityContextHelper.GetEntityConnString())) { var currUserExt = context.SYS_UserExt.Where(p => p.UserCode == currUserCode).FirstOrDefault(); if (currUserExt != null) { emailPassword = Encrypt.TripleDESDecrypting(currUserExt.EmailPassword); } } if (string.IsNullOrWhiteSpace(emailPassword)) { this.Invoke(new MethodInvoker(delegate { this.lblEmailInfo.Text = "邮箱登陆失败!请先在个人设置中设置密码!"; })); return; } IMAPServer.Login(currUserCode + "@ecode.net.cn", emailPassword); //选中收件箱 IMAPServer.SelectFolder("INBOX"); //取出收件箱 var folder = IMAPServer.SelectedFolder; //收件箱邮件总数 //folder.MessagesCount.ToString(); //收件箱未读邮件总数 //folder.RecentMessagesCount.ToString(); //以下开始取出邮件 //首先确定取第x到第n封邮件,"1:*"表示第1封到最后一封 int msgCount = folder.MessagesCount - 20; if (msgCount <= 0) { msgCount = 1; } var seqSet = LumiSoft.Net.IMAP.IMAP_t_SeqSet.Parse(msgCount.ToString() + ":*"); //根据数组中的成员决定取出邮件的那些信息 var imap_t_Fetch_i = new IMAP_t_Fetch_i[] { new IMAP_t_Fetch_i_Envelope(), //邮件的标题、正文等信息 new IMAP_t_Fetch_i_Flags(), //此邮件的标志,应该是已读未读标志 new IMAP_t_Fetch_i_InternalDate(), //貌似是收到的日期 //new IMAP_t_Fetch_i_Rfc822(),//Rfc822是标准的邮件数据流,可以通过Lumisoft.Net.Mail.Mail_Message对象解析出邮件的所有信息(不确定有没有附件的内容)。 new IMAP_t_Fetch_i_Uid() //返回邮件的UID号,UID号是唯一标识邮件的一个号码 }; //创建一个符合lumisoft的回调函数的委托。 //当调用fetch函数完成时,会自动调用用户自定义的函数,这里是Fetchcallback(我自己起的名字,名字无意义,保证参数是object,LumiSoft . Net . EventArgs<IMAP_r_u> 两个就好 EventHandler <LumiSoft.Net.EventArgs <IMAP_r_u> > lumisoftHandler = new EventHandler <LumiSoft.Net.EventArgs <IMAP_r_u> >(Fetchcallback); //把上边定义好的参数传入fetch函数,就会取出邮件 //lumisoftHandler指向的函数在每取出一封邮件的时候会被触发一次 IMAPServer.Fetch(false, seqSet, imap_t_Fetch_i, lumisoftHandler); this.Invoke(new MethodInvoker(delegate { this.lblEmailInfo.Text = ""; this.linkEmailInfo.Text = "您当前共有" + UnReadEmailCount + "封未读邮件!<<click me>>(只搜索最近20封邮件)"; this.linkEmailInfo.Visible = true; this.dgvEmail.DataSource = dtblEmail; })); } catch (Exception ex) { MyLog.LogError("读取未读邮件失败!", ex); if (ex.Message.IndexOf("Invalid login credentials") != -1) { this.Invoke(new MethodInvoker(delegate { this.lblEmailInfo.Text = "邮箱登陆失败!请先在个人设置中设置密码!"; })); } } finally { IMAPServer.Disconnect(); } }
private void imapRecvMail() { using (var imap_client = new IMAP_Client()) { imap_client.Connect(mailAccount.recv_server, mailAccount.recv_port, mailAccount.recv_ssl); // Call Capability even if you don't care about capabilities, it also controls IMAP client features. imap_client.Capability(); imap_client.Login(mailAccount.account, mailAccount.password); imap_client.SelectFolder("INBOX"); try { imap_total = imap_client.SelectedFolder.MessagesCount; workInfo.SetInfo("正在接收邮件列表... 请稍后"); imap_recv_messages = new List<IMAP_r_u_Fetch>(); imap_client.Fetch( false, IMAP_t_SeqSet.Parse("1:*"), new IMAP_t_Fetch_i[]{ new IMAP_t_Fetch_i_Envelope(), new IMAP_t_Fetch_i_Flags(), new IMAP_t_Fetch_i_InternalDate(), new IMAP_t_Fetch_i_Rfc822Size(), new IMAP_t_Fetch_i_Uid() }, this.callback_fetch_message_items ); if (imap_recv_messages.Count == 0) return; workInfo.SetInfo("正在接收邮件... 请稍后"); imap_total = imap_recv_messages.Count; int count = 1; imap_client.FetchGetStoreStream += imap_client_FetchGetStoreStream; foreach (IMAP_r_u_Fetch reps in imap_recv_messages) { if (isStop) return; workInfo.SetProgress(imap_total, count); current_imap_fetch = reps; string text = null; if (reps.Envelope != null) { if (reps.Envelope.Subject != null && reps.Envelope.Subject.IndexOf("&#") != -1) workInfo.AddDetail("正在接收邮件:" + (text = HttpUtility.HtmlDecode(reps.Envelope.Subject)), Colors.Black); else workInfo.AddDetail("正在接收邮件:" + (text = reps.Envelope.Subject), Colors.Black); } //--通知其他订阅人--// XElement el = new XElement("subscribe"); el.SetAttributeValue("total", imap_total); el.SetAttributeValue("count", count); el.SetAttributeValue("account", mailAccount.account); el.SetAttributeValue("type", "accept_mail"); el.SetAttributeValue("detail", "true"); el.SetAttributeValue("principal", Desktop.instance.loginedPrincipal.loginId); el.SetAttributeValue("principal_name", Desktop.instance.loginedPrincipal.name); el.SetAttributeValue("subject", "正在接收邮件:" + text); MessageManager.instance.publishMessage(mailAccount.pubId, "subscribe", el.ToString()); //-----------// imap_client.Fetch( true, IMAP_t_SeqSet.Parse(reps.UID.UID.ToString()), new IMAP_t_Fetch_i[]{ new IMAP_t_Fetch_i_Rfc822Header(), new IMAP_t_Fetch_i_Rfc822() }, this.callback_fetch_message ); count++; try { //唤醒Syncworker SyncWorker.instance.Notify(imap_total); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } imap_client.FetchGetStoreStream -= imap_client_FetchGetStoreStream; if (imap_recv_messages.Count > 0) { SyncWorker.instance.WorkInfo = workInfo; if (SyncWorker.instance.Thread != null) SyncWorker.instance.Thread.Join(); } } catch (Exception ex) { workInfo.SetStatus(false, "邮件接收过程中发生错误:" + ex.Message); hasError = true; } } }