memn 发表于 2015-9-11 10:07:46

接受Exchange邮件+附件代码

        private List<emailMessage> GetEmailsFromExchangeServer(string server, string domain, string username, string password)
      {
            List<emailMessage> ReturnList = new List<emailMessage>();
            try
            {
                ExUser ExchangeUser = new ExUser(server, username, password, domain);
                ExInBox Inbox = new ExInBox(ExchangeUser);
                ExMailMessage[] message = Inbox.GetMessageListFromInbox();
                if (message.Length > 0)
                {
                  for (int i = 0; i < message.Length; i++)
                  {
                        emailMessage tmp = new emailMessage();
                        tmp.mailindex = i+1;
                        tmp.subject = message.Subject;
                        tmp.date = message.Date;
                        tmp.body = message.Body;
                        //tmp.attachments=message.Url
                        string from = message.From;
                        if(from.Contains("<"))
                            from = from.Substring(from.IndexOf('<') + 1, from.IndexOf('>') - 1 - from.IndexOf('<'));
                        tmp.from = from;
                        tmp.displayname = from;
                        string to = message.To;
                        if (to.Contains("<"))
                            to = to.Substring(to.IndexOf('<') + 1, to.IndexOf('>') - 1 - to.IndexOf('<'));
                        tmp.to = to;
                        tmp.displaytoname = to;
                        if (message.HasAttachment)
                        {
                            try
                            {
                              Attachment attach = GetAttachment(message, domain, username, password);
                              if (attach != null)
                              {
                                    tmp.attachmentByte = attach.attachmentByte;
                                    tmp.attachmentName = attach.attachmentName;
                              }
                            }
                            catch(Exception ex)
                            { }
                        }
                        ReturnList.Add(tmp);
                        Inbox.DeleteMessage(message.Url);
                  }
                }
            }
            catch(Exception e)
            {}
            return ReturnList;
      }

  
        private Attachment GetAttachment(ExMailMessage mailMessage, string domain, string username, string password)
      {
            // Variables.
            Attachment result = null;
            System.Net.HttpWebRequest Request;
            System.Net.WebResponse Response;
            System.Net.CredentialCache MyCredentialCache;
            System.IO.Stream ResponseStream = null;
            System.Xml.XmlDocument ResponseXmlDoc = null;
            System.Xml.XmlNode root = null;
            System.Xml.XmlNamespaceManager nsmgr = null;
            System.Xml.XmlNodeList PropstatNodes = null;
            System.Xml.XmlNodeList HrefNodes = null;
            System.Xml.XmlNode StatusNode = null;
            System.Xml.XmlNode PropNode = null;
              string[] _attachmentName = null;
            string[] _realAttachmentName = null;
            System.Xml.XmlNode NameNode = null;
            try
            {
                // Create a new CredentialCache object and fill it with the network
                // credentials required to access the server.
                MyCredentialCache = new System.Net.CredentialCache();
                MyCredentialCache.Add(new System.Uri(mailMessage.Url),
                  "NTLM",
                  new System.Net.NetworkCredential(username, password, domain)
                  );
                  // Create the HttpWebRequest object.
                Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(mailMessage.Url);
                  // Add the network credentials to the request.
                Request.Credentials = MyCredentialCache;
                  // Specify the method.
                Request.Method = "X-MS-ENUMATTS";
                  // Send the X-MS-ENUMATTS method request and get the
                // response from the server.
                Response = (HttpWebResponse)Request.GetResponse();
                  // Get the XML response stream.
                ResponseStream = Response.GetResponseStream();
                  // Create the XmlDocument object from the XML response stream.
                ResponseXmlDoc = new System.Xml.XmlDocument();
                  // Load the XML response stream.
                ResponseXmlDoc.Load(ResponseStream);
                  // Get the root node.
                root = ResponseXmlDoc.DocumentElement;
                  // Create a new XmlNamespaceManager.
                nsmgr = new System.Xml.XmlNamespaceManager(ResponseXmlDoc.NameTable);
                  // Add the DAV: namespace, which is typically assigned the a: prefix
                // in the XML response body.The namespaceses and their associated
                // prefixes are listed in the attributes of the DAV:multistatus node
                // of the XML response.
                nsmgr.AddNamespace("a", "DAV:");
                  // Add the http://schemas.microsoft.com/mapi/proptag/ namespace, which
                // is typically assigned the d: prefix in the XML response body.
                nsmgr.AddNamespace("d", "http://schemas.microsoft.com/mapi/proptag/");
                nsmgr.AddNamespace("e", "urn:schemas:httpmail:");
                // Use an XPath query to build a list of the DAV:propstat XML nodes,
                // corresponding to the returned status and properties of
                // the file attachment(s).
                PropstatNodes = root.SelectNodes("//a:propstat", nsmgr);
                  // Use an XPath query to build a list of the DAV:href nodes,
                // corresponding to the URIs of the attachement(s) on the message.
                // For each DAV:href node in the XML response, there is an
                // associated DAV:propstat node.
                HrefNodes = root.SelectNodes("//a:href", nsmgr);
                  // Attachments found?
                if (HrefNodes.Count > 0)
                {
                  _attachmentName = new string;
                  _realAttachmentName = new string;
                  // Display the number of attachments on the message.
                  // Iterate through the attachment properties.
                  for (int i = 0; i < HrefNodes.Count; i++)
                  {
                        // Use an XPath query to get the DAV:status node from the DAV:propstat node.
                        StatusNode = PropstatNodes.SelectSingleNode("a:status", nsmgr);
                          // Check the status of the attachment properties.
                        if (StatusNode.InnerText != "HTTP/1.1 200 OK")
                        {
                            return null;
                        }
                        else
                        {
                            // Get the CdoPR_ATTACH_FILENAME_W MAPI property tag,
                            // corresponding to the attachment file name.The
                            // http://schemas.microsoft.com/mapi/proptag/ namespace is typically
                            // assigned the d: prefix in the XML response body.
                            NameNode = PropstatNodes.SelectSingleNode("a:prop/d:x3704001f", nsmgr);
                            // Get the CdoPR_ATTACH_SIZE MAPI property tag,
                            // corresponding to the attachment file size.
                            PropNode = PropstatNodes.SelectSingleNode("a:prop/d:x0e200003", nsmgr);
                            string size;
                            if (Convert.ToInt32(PropNode.InnerText) > 1024 * 1224)
                            {
                              size = (Convert.ToInt32(PropNode.InnerText) / (1024 * 1024)).ToString() + "M";
                            }
                            else if (Convert.ToInt32(PropNode.InnerText) > 1024)
                            {
                              size = (Convert.ToInt32(PropNode.InnerText) / 1024).ToString() + "KB";
                            }
                            else
                            {
                              size = PropNode.InnerText + "B";
                            }
                            int index = HrefNodes.InnerText.LastIndexOf('/') + 1;
                            string attachmentName = HrefNodes.InnerText.Substring(index);
                            int mLastIndex = attachmentName.LastIndexOf('.');
                            string mMainName = attachmentName.Substring(0, mLastIndex);
                            //mMainName = Server.UrlDecode(mMainName);
                            int mExtLength = attachmentName.Length - mLastIndex;
                            string mExtName = attachmentName.Substring(mLastIndex, mExtLength);
                            string LAttachment= mailMessage.Url + "/" + mMainName +mExtName ;
                            _attachmentName = mailMessage.Url + "/" + mMainName + mExtName + "/C58EA28C-18C0-4a97-9AF2-036E93DDAFB3/" + mMainName + mExtName + "?attach=1";
                            _realAttachmentName = PropstatNodes.SelectSingleNode("a:prop/e:attachmentfilename", nsmgr).InnerText;
                        }
                  }
                  }
                  // Clean up.
                ResponseStream.Close();
                Response.Close();
                result = this.GetAttachmentFile(mailMessage, domain, username, password, HrefNodes.Count, _attachmentName,_realAttachmentName);
            }
            catch (Exception ex)
            {
                // Catch any exceptions. Any error codes from the X-MS-ENUMATTS
                // method request on the server will be caught here, also.
              }
            return result;
      }

        private Attachment GetAttachmentFile(ExMailMessage mailMessage, string domain, string username, string password, int Count, string[] _attachmentName, string[] _realAttachmentName)
      {
            //_attachmentName = "http://mail.blifax.com/Exchange/HongC/Inbox/blifax.com.EML/1_multipart_xF8FF_3_1.0.0.15.sql";
            Attachment attach = new Attachment();
            System.Net.HttpWebRequest Request;
            System.Net.WebResponse Response;
            System.Net.CredentialCache MyCredentialCache;
            Stream ResponseStream = null;
            try
            {
                for(int i=0;i<_attachmentName.Length;i++)
                {
                  // Create a new CredentialCache object and fill it with the network
                  // credentials required to access the server.
                  MyCredentialCache = new System.Net.CredentialCache();
                  MyCredentialCache.Add(new System.Uri(_attachmentName),
                        "NTLM",
                        new System.Net.NetworkCredential(username, password, domain)
                        );
                    // Create the HttpWebRequest object.
                  Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(_attachmentName);
                  Request.UnsafeAuthenticatedConnectionSharing = true;
                  // Add the network credentials to the request.
                  Request.Credentials = MyCredentialCache;
                    // Specify the method.
                  Request.Method = "GET";
                    // Send the X-MS-ENUMATTS method request and get the
                  // response from the server.
                  Response = (HttpWebResponse)Request.GetResponse();
                  
                  // Get the XML response stream.
                  ResponseStream = Response.GetResponseStream();
                    MemoryStream ms = new MemoryStream();
                  StreamReader sr = new StreamReader(ResponseStream);
                  byte[] buffer = new byte;
                  int count = ResponseStream.Read(buffer, 0, 256);
                  while (count > 0)
                  {
                        ms.Write(buffer, 0, count);
                        count = ResponseStream.Read(buffer, 0, 256);
                  }
                  byte[] bs = ms.ToArray();
                  attach.attachmentByte = bs;
                  attach.attachmentName = _realAttachmentName;
                  ResponseStream.Close();
                  Response.Close();
                }
                return attach;
            }
            catch(Exception e)
            {
                return attach;
            }
      }

页: [1]
查看完整版本: 接受Exchange邮件+附件代码