C#访问hotmail邮件

如何使用程序来访问HOTMAIL的邮件

using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Web;

namespace Hotmail
{
 /// <summary>
 /// HotmailProxy is able to speak HttpMail to various
 /// Hotmail servers across the world.
 /// </summary>
 public class HotmailProxy
 {
  /// <summary>
  /// Storage area for cookies.
  /// </summary>
  private CookieContainer ccContainer;

  /// <summary>
  /// Creates a new instance of HotmailHttp.
  /// </summary>
  public HotmailProxy()
  {
   Trace.WriteLine("Creating new instance.");
   ccContainer = new CookieContainer();
  }

  /// <summary>
  /// Sends the given request to the given destination
  /// and returns the answer from the server.
  /// </summary>
  /// <param name="request">The request to send.</param>
  /// <param name="destination">The destination to send the request to.</param>
  /// <returns>The answer from the remote host.</returns>
  public string SendRequest(string request, Uri destination)
  {
   // pass along
   return SendRequest(request,destination,null);
  }

  /// <summary>
  /// Sends the given request to the given destination
  /// and returns the answer from the server.
  /// </summary>
  /// <param name="request">The request to send.</param>
  /// <param name="destination">The destination to send the request to.</param>
  /// <param name="credential">The network credentials to use with the request.</param>
  /// <returns>The answer from the remote host.</returns>
  public string SendRequest(string request, Uri destination, NetworkCredential credential)
  {
   // Verify input
   if(request == null || request.Trim().Length == 0)
    throw new ArgumentNullException("request");
   else if (destination == null)
    throw new ArgumentNullException("destination");
   else
   {
    // Get byte[] and send the request using private method.
    byte[] xmlBytes = Encoding.ASCII.GetBytes(request);
    return SendRequestTo(xmlBytes,destination, credential);
   }
  }

  /// <summary>
  /// Sends the given byte[] to the given remote host using
  /// authentication with the supplied credentials.
  /// </summary>
  /// <param name="requestBytes"></param>
  /// <param name="destination"></param>
  /// <param name="credential"></param>
  /// <returns></returns>
  private string SendRequestTo(byte[] requestBytes, Uri destination, NetworkCredential credential)
  {
   Trace.WriteLine("Sending request to url:" + destination.AbsoluteUri);

   // Build the request.
   HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(destination);
   webRequest.Method = "PROPFIND";
   webRequest.Accept = "*/*";
   webRequest.AllowAutoRedirect = false;
   webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR v1.1.4322)";
   webRequest.CookieContainer = new CookieContainer();
   webRequest.ContentLength = requestBytes.Length;
   webRequest.ContentType = "text/xml";
   // Set the credentials
   webRequest.Credentials = credential;
   // Add cookies for this request
   webRequest.CookieContainer.Add(ccContainer.GetCookies(destination));

   try
   {
    // Write the request
    Stream reqStream = webRequest.GetRequestStream();
    reqStream.Write(requestBytes,0,requestBytes.Length);
    reqStream.Close();
    // Get a response
    HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
    if (webRequest.HaveResponse)
    {
     // Handle returned cookies
     foreach(Cookie retCookie in webResponse.Cookies)
     {
      bool cookieFound = false;
      
      foreach(Cookie oldCookie in ccContainer.GetCookies(destination))
      {
       if (retCookie.Name.Equals(oldCookie.Name))
       {
        oldCookie.Value = retCookie.Value;
        cookieFound = true;
       }
      }
      if (!cookieFound)
       ccContainer.Add(retCookie);
      
     }     
     // Handle redirection headers
     if ((webResponse.StatusCode == HttpStatusCode.Found) ||
      (webResponse.StatusCode == HttpStatusCode.Redirect) ||
      (webResponse.StatusCode == HttpStatusCode.Moved) ||
      (webResponse.StatusCode == HttpStatusCode.MovedPermanently))
     {    
      WebHeaderCollection headers = webResponse.Headers;
      return SendRequestTo(requestBytes,new Uri(headers["location"]),credential); 
     }
     // Read response
     StreamReader stream = new StreamReader(webResponse.GetResponseStream());
     string responseString = stream.ReadToEnd();
     stream.Close();
   
     return responseString;
    }
    // No response
    throw new ApplicationException("No response received from host.");
   }
   catch(WebException e)
   {
    // Error occured
    Trace.WriteLine("Exception occured " + e.Message);
    throw new ApplicationException("Exception occured while sending request."+e.Message,e);
   }
   
  }
 }
}
using System;
using System.Diagnostics;
using System.Net;
using System.Xml;

namespace Hotmail
{
 public class HotmailClient
 {
  #region Class Instances and Properties
  /// <summary>
  /// The Http proxy used for Hotmail
  /// </summary>
  private HotmailProxy hHttp   = null;
  /// <summary>
  /// Indicator if connected to remote host.
  /// </summary>
  private bool connected    = false;
  #endregion

  #region Public Interface( Constructor, Connect, Disconnect, RetrieveFilledMailBox)
  /// <summary>
  /// Create a new instance of HotmailClient.
  /// </summary>
  public HotmailClient()
  {
  }

  /// <summary>
  /// Connect this client to the remote hotmail host and
  /// retrieve a list of mailboxes.
  /// </summary>
  /// <param name="username">The username to connect with.</param>
  /// <param name="password">The password to connect with.</param>
  public void Connect(string username, string password)
  {
   // Verify input
   if (username == null || username.Trim().Length == 0)
    throw new ArgumentNullException("username");
   if (password == null || password.Trim().Length == 0)
    throw new ArgumentNullException("password");
   if (username.IndexOf("@") == -1)
    throw new ArgumentException("Illegal username, must contain an @ sign: (user@hotmail.com).");
   // Create the specialized Http client and the neccesary credentials
   hHttp = new HotmailProxy();
   NetworkCredential credentials = new NetworkCredential(username,password,null);
   // Build the query for the msgfolderroot
   string query = "<?xml version='1.0'?>" +
    "<D:propfind xmlns:D='DAV:' " +
    "xmlns:h='http://schemas.microsoft.com/hotmail/' " +
    "xmlns:hm='urn:schemas:httpmail:'>" +
    "<D:prop>"     +
    "<hm:msgfolderroot/>" +
    "</D:prop>"     +
    "</D:propfind>";
   // Connect
   try
   {
    // Get a response from the query, connect to the hotmail entry page.
    string hotmailEntryPoint = "http://services.msn.com/svcs/hotmail/httpmail.asp";
    string response = hHttp.SendRequest(query, new Uri(hotmailEntryPoint),credentials);
    // Verify response
    if (response == null || response.Trim().Length == 0)
     throw new ApplicationException("No response received from host.");
    // Parse the response, further verifying it.
    Uri folderRootUri = ParseConnectResponse(response);
    // Obtain available folders using folderRootUrl
    RetrieveMailboxes(folderRootUri);
    // Now we're connected
    connected = true;
   }
   catch(Exception e)
   {
    // Something went wrong.
    throw new ApplicationException("Exception occured while connecting to remote host.",e);
   }
  }
  #endregion

  #region Private Interface( ParseConnectResponse, ParseFillResponse, RetrieveMailboxes, CreateNamespaceManager)

  /// <summary>
  /// This method parses the response from the server from
  /// the Connect() call, and returns the Uri contained in
  /// the msgfolderroot. This is the root for all mailboxes.
  /// </summary>
  /// <param name="response">The response from the remote host.</param>
  /// <returns>The Uri contained in msgfolderroot.</returns>
  private Uri ParseConnectResponse(string response)
  {
   try
   {
    // Load response into XmlDocument
    XmlDocument dom = new XmlDocument();
    dom.LoadXml(response);
    // Query XmlDocument for msgfolderroot node.
    string xpath = "//hm:msgfolderroot";
    XmlNamespaceManager context = CreateNamespaceManager(dom.NameTable);
    XmlNode folderRoot = dom.SelectSingleNode(xpath,context);
    // Verify node
    if (folderRoot == null)
     throw new ApplicationException("Node '" + xpath + "' not found.");
    // Get node text and verify,
    string folderRootUrl = folderRoot.InnerText;
    if ((folderRootUrl == null) || (folderRootUrl.Trim().Length == 0))
     throw new ApplicationException("No url found in node '" + xpath + "'.");
    try
    {
     // Return the uri, this may result in a UriFormatException
     return new Uri(folderRootUrl);
    }
    catch
    {
     throw new ApplicationException("Url found in node '" + xpath + "' is invalid:" + folderRootUrl);
    }
   }
   catch(Exception e)
   {
    // Something went wrong.
    throw new ApplicationException("Error occured while parsing connect response.",e);
   }
  }
  
  /// <summary>
  /// Requests available mailboxes from the remote host using the
  /// given msgfolderroot url, and parses the response into
  /// the mailBoxes container.
  /// </summary>
  /// <param name="folderRootUrl">The Uri of the msgfolderroot.</param>
  private void RetrieveMailboxes(Uri folderRootUrl)
  {
   try
   {
    // Build the needed query
    string query = "<?xml version='1.0'?>" +
     "<D:propfind xmlns:D='DAV:' xmlns:hm='urn:schemas:httpmail:'>" +
     "<D:prop>"    +
     "<D:displayname/>" +
     "<hm:special/>"  +
     "<hm:unreadcount/>" +
     "<D:visiblecount/>" +
     "</D:prop>"    +
     "</D:propfind>";
    // Get a response from server
    string response = hHttp.SendRequest(query,folderRootUrl);
    // Verify response
    if (response == null || response.Trim().Length == 0)
     throw new ApplicationException("No response received from host."); 
    // Load response into XmlDocument
    XmlDocument dom = new XmlDocument();
    dom.LoadXml(response);
    // Query XmlDocument for all mailboxes using XPath
    string xpath = "//D:response";
    XmlNamespaceManager context = CreateNamespaceManager(dom.NameTable);
    XmlNodeList mailBoxNodes = dom.SelectNodes(xpath,context);
    // Parse each node found
    foreach(XmlNode mailBoxNode in mailBoxNodes)
    {  
     try
     {
      // Direct mapping using XPath, should not result in any errors
      // as long as Hotmail keeps it protocol the same.
      string type = mailBoxNode.SelectSingleNode("descendant::hm:special",context).InnerText;     
      string nameUrl = mailBoxNode.SelectSingleNode("descendant::D:href",context).InnerText;
      int visibleCount = Int32.Parse(mailBoxNode.SelectSingleNode("descendant::D:visiblecount",context).InnerText);
      int unreadCount = Int32.Parse(mailBoxNode.SelectSingleNode("descendant::hm:unreadcount",context).InnerText);
      // Add the mailbox
      Console.WriteLine("MailBox found: " + type + "/r/n" +
       "/turl: " + nameUrl + "/r/n" +
       "/tVisible: " + visibleCount + "/r/n" +
       "/tUnread: " + unreadCount + "/r/n");

     }
     catch(Exception e)
     {
      Console.WriteLine("Exception occured while obtaining mailbox info: " + e.Message);
     }
    }
   }
   catch(Exception e)
   {
    // Something went wrong.
    throw new ApplicationException("Error occured while retrieving available mailboxes.",e);
   }
  }
  
  /// <summary>
  /// Helper method to create the XmlNamespaceManager needed for
  /// correctly querying the response using XPath.
  /// </summary>
  /// <param name="table"></param>
  /// <returns></returns>
  private XmlNamespaceManager CreateNamespaceManager(XmlNameTable table)
  {
   XmlNamespaceManager m = new XmlNamespaceManager(table);
   m.AddNamespace("hm","urn:schemas:httpmail:");
   m.AddNamespace("D","DAV:");
   m.AddNamespace("m","urn:schemas:mailheader:");
   m.AddNamespace("c","urn:schemas:contacts:");
   m.AddNamespace("h","http://schemas.microsoft.com/hotmail/");
   return m;
  }
  #endregion

 }
}

程序进入点

private void button1_Click(object sender, System.EventArgs e)
  {
   HotmailClient client=new HotmailClient();
   client.Connect("xxxx@hotmail.com","urPassword");
  }

### 回答1: 作为一个发邮件的软件,Windows上有多种选择。其中之一是使用Microsoft Outlook,它是Windows操作系统自带的邮件客户端。Outlook提供了强大的电子邮件管理和发送功能,容易上手且适用于个人和专业用户。 首先,用户可以通过Outlook设置一个或多个电子邮件帐户,包括个人邮件和工作邮件,以便能够在同一个界面中管理所有邮件。用户可以输入用户名和密码,然后Outlook将拉取最新的邮件到收件箱中。此外,Outlook还支持多种邮件服务提供商,如Gmail、Hotmail、Yahoo等。 然后,用户可以轻松地创建、撰写和发送电子邮件。Outlook提供了一个可视化的编辑界面,用户可以在其中填写收件人、抄送、密送等信息。用户还可以附加文件、插入图片和显示格式标记,以使邮件内容更加丰富和易于阅读。Outlook还提供自动保存功能,以免用户遗漏重要内容。 Outlook还具有强大的邮件筛选和管理功能。用户可以使用标签和文件夹来组织邮件,并进行快速搜索和过滤。Outlook还支持自动规则,可以根据用户设置的条件自动将邮件转移到指定的文件夹,以便更好地管理和整理邮件。 此外,Outlook还支持日历、任务、联系人等功能。用户可以在日历中安排会议和活动,并与他人共享。任务功能可以帮助用户制定和跟踪待办事项。联系人管理功能使用户可以轻松地保存和查找联系信息,以便随时与他人联系。 总的来说,通过使用Microsoft Outlook,用户可以方便地管理和发送电子邮件,并在同一个应用程序中访问其他有用的工具和功能。无论是作为个人用户还是商务用户,Outlook都提供了一套强大而全面的解决方案。 ### 回答2: Windows操作系统下可以使用C#编程语言来开发一个发邮件的软件。首先,需要使用Visual Studio工具创建一个新的Windows窗体应用程序项目。 接下来,可以在窗体中添加邮件发送的相关控件,如文本框用于输入收件人地址、主题和邮件内容,按钮用于触发发送邮件的事件等。通过控件属性的设置,可以调整控件的位置、大小和样式,使其符合软件设计的要求。 在程序代码中,需要引入System.Net命名空间,在命名空间下的SmtpClient类和MailMessage类可以实现邮件发送功能。使用SmtpClient类可以连接SMTP服务器,并提供发送邮件的相关方法。MailMessage类用于创建邮件消息,设置收件人、主题、内容等信息。 创建发送邮件的事件处理方法,当按钮被点击时,该方法将被触发。在该方法中,首先实例化MailMessage类,并设置邮件的相关信息,如收件人地址、主题和内容。然后,实例化SmtpClient类,并设置SMTP服务器的相关信息,如服务器地址、端口号和是否使用SSL等。最后,调用SmtpClient类的Send方法将邮件发送出去。 为了增加用户交互性,也可以在用户发送邮件后显示一个提示框,告知发送是否成功,并根据结果做出不同的处理。 最后,进行调试和测试,确保发邮件软件的功能正常。可以使用自己的邮箱或者其他邮箱的测试账号,发送邮件到指定的收件人地址,观察是否成功发送。 总结,通过使用C#编程语言结合Windows窗体应用程序开发工具,可以轻松创建一个简单的发邮件的软件,满足日常发送邮件的需求。 ### 回答3: 要编写一个用于发送邮件的Windows软件,需要以下步骤和功能: 1. 用户界面设计:设计一个直观且易于使用的用户界面,包括菜单栏、工具栏和主窗口。 2. 用户身份验证:提供用户登录功能,要求用户输入邮箱地址和密码以验证身份。 3. 邮件撰写:在主窗口中提供邮件撰写区域,包括收件人、主题和邮件正文。用户可以输入多个收件人,使用逗号或分号进行分隔。 4. 附件支持:允许用户添加附件到邮件中,可以通过菜单栏或工具栏提供“添加附件”选项,用户通过文件选择器选择要添加的文件。 5. 发送邮件:提供发送邮件功能,用户点击“发送”按钮后,软件会将邮件发送到SMTP服务器并进行传输。 6. 邮件保存:提供“保存草稿”功能,用户可以将草稿邮件保存在本地计算机上,以便之后打开并继续编辑。 7. 联系人管理:允许用户管理联系人列表,包括添加、编辑和删除联系人。用户可以从联系人列表中选择收件人。 8. 邮件检索:提供邮件检索功能,用户可以通过输入关键字来搜索已发送或已接收的邮件。 9. 邮件模板:允许用户保存常用的邮件作为模板,以便将来使用。用户可以加载模板并进行修改,以适应不同的情况。 10. 设置选项:提供设置选项,例如选择默认的字体和邮件签名,设置发送和接收服务器的相关参数。 以上是编写Windows发邮件软件的一些基本功能和步骤。当然,根据需求和设计要求,还可以进一步扩展和优化软件的功能和性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值