接受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[i].Subject;
                        tmp.date = message[i].Date;
                        tmp.body = message[i].Body;
                        //tmp.attachments=message[0].Url
                        string from = message[i].From;
                        if(from.Contains("<"))
                            from = from.Substring(from.IndexOf('<') + 1, from.IndexOf('>') - 1 - from.IndexOf('<'));
                        tmp.from = from;
                        tmp.displayname = from;
                        string to = message[i].To;
                        if (to.Contains("<"))
                            to = to.Substring(to.IndexOf('<') + 1, to.IndexOf('>') - 1 - to.IndexOf('<'));
                        tmp.to = to;
                        tmp.displaytoname = to;
                        if (message[i].HasAttachment)
                        {
                            try
                            {
                                Attachment attach = GetAttachment(message[i], domain, username, password);
                                if (attach != null)
                                {
                                    tmp.attachmentByte = attach.attachmentByte;
                                    tmp.attachmentName = attach.attachmentName;
                                }
                            }
                            catch(Exception ex)
                            { }
                        }
                        ReturnList.Add(tmp);
                        Inbox.DeleteMessage(message[i].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[HrefNodes.Count];
                    _realAttachmentName = new string[HrefNodes.Count];
                    // 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[i].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[i].SelectSingleNode("a:prop/d:x3704001f", nsmgr);
                            // Get the CdoPR_ATTACH_SIZE MAPI property tag,
                            // corresponding to the attachment file size.
                            PropNode = PropstatNodes[i].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[i].InnerText.LastIndexOf('/') + 1;
                            string attachmentName = HrefNodes[i].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[i] = mailMessage.Url + "/" + mMainName + mExtName + "/C58EA28C-18C0-4a97-9AF2-036E93DDAFB3/" + mMainName + mExtName + "?attach=1";
                            _realAttachmentName[i] = PropstatNodes[i].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[0] = "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[i]),
                        "NTLM",
                        new System.Net.NetworkCredential(username, password, domain)
                        );

                    // Create the HttpWebRequest object.
                    Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(_attachmentName[i]);
                    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[256];
                    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[i];
                    ResponseStream.Close();
                    Response.Close();
                }
                return attach;
            }
            catch(Exception e)
            {
                return attach;
            }
        }

转载于:https://www.cnblogs.com/chenhong/archive/2008/07/28/1254954.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值