/// <summary> /// Connects to email server. /// </summary> /// <param name="useSSL">if set to <c>true</c> [use SSL].</param> /// <returns></returns> private bool ConnectToEmailServer(bool useSSL) { Disconnect(); if (_client != null && !_client.IsDisposed) { _client.Dispose(); } _client = new IMAP_Client(); try { if (useSSL) { _client.Connect(_settings.Server, WellKnownPorts.IMAP4_SSL, true); //port 993 } else { _client.Connect(_settings.Server, WellKnownPorts.IMAP4, false); //port 143 } if (_settings.Security == SecurityEnum.TLS) { _client.StartTls(); } _client.Login(_settings.User, _settings.Pass); return(true); } catch (Exception ex) { //Debug.WriteLine(ex.Message); AppJournal.Write("EmailImapTransport: ConnectToEmailServer " + ex.Message); return(false); } }
/// <summary> /// Удаляет все сообщения из IMAP папки по фильтру subject /// </summary> public static void ClearImapFolder(string mailbox, string password, string folder, string subject) { using (var imapClient = new IMAP_Client()) { imapClient.Connect(Settings.Default.IMAPHost, Convert.ToInt32(Settings.Default.IMAPPort)); imapClient.Authenticate(mailbox, password); imapClient.SelectFolder(folder); var sequenceSet = new IMAP_SequenceSet(); sequenceSet.Parse("1:*", Int64.MaxValue); var items = String.IsNullOrEmpty(subject) ? imapClient.FetchMessages(sequenceSet, IMAP_FetchItem_Flags.UID, false, false) : imapClient.FetchMessages(sequenceSet, IMAP_FetchItem_Flags.UID | IMAP_FetchItem_Flags.Envelope, false, false); //производим фильтрацию, если параметр subject установлен if (!String.IsNullOrEmpty(subject) && items != null && items.Length > 0) { items = items .Where(i => i.Envelope.Subject?.Equals(subject, StringComparison.CurrentCultureIgnoreCase) == true) .ToArray(); } if ((items != null) && (items.Length > 0)) { var sequenceMessages = new IMAP_SequenceSet(); sequenceMessages.Parse(String.Join(",", items.Select(i => i.UID.ToString()).ToArray()), long.MaxValue); imapClient.DeleteMessages(sequenceMessages, true); } } }
public void functionIMAP() { using (IMAP_Client c = new IMAP_Client()) { try { //连接IMAP_Client服务器 c.Connect("outlook.office365.com", 993, true); //验证用户身份 c.Login(UserName, Pwd); //邮件密码/smtp、pop3授权码 //MessageBox.Show("数量:" + c.GetFolders(null).ToList().Count().ToString()); c.GetFolders(null).ToList().ForEach(f => { Console.WriteLine(f.FolderName); var s = c.FolderStatus(f.FolderName); s.ToList().ForEach(sIt => { MessageBox.Show(string.Format("总数:{0},未读:{1},最近{2}", sIt.MessagesCount, sIt.MessagesCount, sIt.UnseenCount)); }); }); } catch (Exception e) { MessageBox.Show(e.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); }
/// <summary> /// Get connect from yandex. /// </summary> /// <param name="login">Login from email.</param> /// <param name="password">Password from email.</param> public void connect(string login, string password) { client = new IMAP_Client(); client.Connect("imap.yandex.ru", 993, true); client.Login(login, password); Console.Out.WriteLine("метод connect"); }
public override Server creack(String ip, int port, String username, String password, int timeOut) { IMAP_Client conn = null; Server server = new Server(); try { conn = new IMAP_Client(); //与IMAP服务器建立连接 conn.Timeout = timeOut; conn.Connect(ip, port, true); if (conn.IsConnected) { conn.Login(username, password); if (conn.IsAuthenticated) { server.isSuccess = conn.IsAuthenticated; server.banner = conn.GreetingText; } } } catch (Exception e) { throw e; } finally { if (conn != null) { conn.Disconnect(); } } return(server); }
public static void StoreMessage(string mailbox, string password, string folder, byte[] messageBytes) { using (var imapClient = new IMAP_Client()) { imapClient.Connect(Settings.Default.IMAPHost, Convert.ToInt32(Settings.Default.IMAPPort)); imapClient.Authenticate(mailbox, password); imapClient.SelectFolder(Settings.Default.IMAPSourceFolder); imapClient.StoreMessage(folder, messageBytes); } }
public IMAP_Client loginAs(string login, string password) { IMAP_Client client = new IMAP_Client(); client.Connect("imap.yandex.ru", 993, true); client.Login(login, password); client.SelectFolder("INBOX"); Console.Out.WriteLine("метод loginAS"); return(client); }
public void Connect(String server, String User, String pass, int port, bool useSSl) { try { Client = new IMAP_Client(); Client.Connect(server, port, useSSl); Client.Login(User, pass); _IsConnected = true; } catch (Exception exe) { throw new EMailException { ExceptionType = EMAIL_EXCEPTION_TYPE.ERROR_ON_CONNECTION, InnerException = exe }; } }
public void connect() { IMAP_Client client = new IMAP_Client(); client.Connect("imap.yandex.ru", 995, true); client.Login("testkeepteam1", "testmail"); client.SelectFolder("Inbox"); /* client * client.Fetch(false, * IMAP_t_SeqSet.Parse("2:1"), * new IMAP_t_Fetch_i() {new IMAP_t_Fetch_i_Envelope()}, * new EventHandler(Of LumiSoft.Net.EventArgs(Of IMAP_r_u))(AddressOf client_Fetch)); * */ }
public static List <IMAP_FetchItem> CheckImapFolder(string mailbox, string password, string folder) { using (var imapClient = new IMAP_Client()) { imapClient.Connect(Settings.Default.IMAPHost, Convert.ToInt32(Settings.Default.IMAPPort)); imapClient.Authenticate(mailbox, password); imapClient.SelectFolder(folder); var sequenceSet = new IMAP_SequenceSet(); sequenceSet.Parse("1:*", Int64.MaxValue); var items = imapClient.FetchMessages(sequenceSet, IMAP_FetchItem_Flags.UID | IMAP_FetchItem_Flags.Envelope, false, false); if ((items != null) && (items.Length > 0)) { return(items.ToList()); } } return(new List <IMAP_FetchItem>()); }
public IMAP_Client loginMail(string userName, string psw, string service, bool ssl, int port) { IMAP_Client imapc = new IMAP_Client(); try { if (imapc.IsConnected) { imapc.Disconnect(); } imapc.Connect(service, port, ssl); imapc.Login(userName, psw); } catch (Exception ex) { Console.WriteLine("ErrConnect:" + ex.Message); } return(imapc); }
public override void Open() { Logger.Debug("Opening IMAP connection {0}", LogSource.Channel, UniqueId); if (!(channelState == ChannelState.Closed || channelState == ChannelState.Broken)) { Logger.Debug("SUCCESS Connection was allready open {0}", LogSource.Channel, UniqueId); return; } channelState = ChannelState.Connecting; client = new IMAP_Client(); if ("/Settings/Channels/LoggerEnabled".AsKey(false)) { client.Logger = new LumiSoft.Net.Log.Logger(); client.Logger.WriteLog += (sender, e) => Logger.Debug(e.LogEntry.Text.Replace("{", "{{").Replace("}", "}}"), LogSource.Channel); } try { client.Connect(Hostname, Port, IsSecured); channelState = ChannelState.Connected; } catch (Exception ex) { channelState = ChannelState.Closed; Logger.Debug("Unable to connect to server. Exception = {0}", LogSource.Channel, ex); throw new ChannelException("Unable to connect to server", ex); } Logger.Debug("SUCCESS Opening connection {0}", LogSource.Channel, UniqueId); }
public void ConnectToIMAP() { _imapClient.Connect(Settings.Default.IMAPHost, 143); ImapReader.IMAPAuth(_imapClient); _imapClient.SelectFolder(Settings.Default.IMAPSourceFolder); }
//#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; } } }