使用c#+IMap实现收取163邮件

时间:2019-04-13
本文章向大家介绍使用c#+IMap实现收取163邮件,主要包括使用c#+IMap实现收取163邮件使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

最近我要做一个爬虫。这个爬虫需要如下几个步骤:

1 填写注册内容(需要邮箱注册)

2 过拖拽验证码(geetest)

3 注册成功会给邮箱发一封确认邮箱

4 点击确认邮箱中的链接 完成注册

我这里就采用163邮箱注册。

邮箱协议有 pop3 和 imap 和 smtp

我试了pop3  不能够筛选邮件 例如筛选未读 和 发件人这2个条件 所以放弃用pop3

imap协议是支持的。

我就找了一个开源的第三方lib:S22.Imap

用法很简单:

public void Test163()
    {
      var imapServer = "imap.163.com";
      var port = 993;
      using (ImapClient client = new ImapClient(imapServer, port, "xxxx@163.com", "pwd", AuthMethod.Login, true))
      {
        // Returns a collection of identifiers of all mails matching the specified search criteria.
        IEnumerable<uint> uids = client.Search(SearchCondition.Unseen());
        // Download mail messages from the default mailbox.
        IEnumerable<MailMessage> messages = client.GetMessages(uids,FetchOptions.HtmlOnly);

        Console.WriteLine("We are connected!");
      }

    }
 

发现 在login的时候 报错了:

提示“NO Select Unsafe Login. Please contact kefu@188.com for help”。

163邮箱也会收到一个告警邮件

经过查证 发现得需要在发送 login 命令之前 得先发送 id 命令

至于为什么要这么做 我的理解是得先伪装成普通的客户端吧(有理解错误请指出谢谢)

我fork了一份SS2.imap的代码 打算兼容163的这个特殊情况改掉源码

然后走Login方法就不会报错了

 Github地址:https://github.com/yuzd/S22.Imap

另外附上使用smtp发送邮件的实例
protected void Button2_Click(object sender, EventArgs e)
  {
    System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
    client.Host = "smtp.163.com";//使用163的SMTP服务器发送邮件
    client.UseDefaultCredentials = true; 
    client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; 
    client.Credentials = new System.Net.NetworkCredential("用户名", "密码");//163的SMTP服务器需要用163邮箱的用户名和密码作认证,如果没有需要去163申请个,                                     
    //这里假定你已经拥有了一个163邮箱的账户,用户名为abc,密码为******* 
    System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
    Message.From = new System.Net.Mail.MailAddress("上述用户名密码所对应的邮箱地址");//这里需要注意,163似乎有规定发信人的邮箱地址必须是163的,而且发信人的邮箱用户名必须和上面SMTP服务器认证时的用户名相同                                
    //因为上面用的用户名abc作SMTP服务器认证,所以这里发信人的邮箱地址也应该写为abc@163.com
    Message.To.Add("目标邮箱地址");//将邮件发送给Gmail
    //Message.To.Add("123456@qq.com");//将邮件发送给QQ邮箱
    Message.Subject = "customer feedback";
    Message.Body = "customer feedback content"; 
    Message.SubjectEncoding = System.Text.Encoding.UTF8;
    Message.BodyEncoding = System.Text.Encoding.UTF8;
    Message.Priority = System.Net.Mail.MailPriority.High;
    Message.IsBodyHtml = true;
    client.Send(Message);
  }