设为首页 收藏本站
查看: 733|回复: 0

[经验分享] 接受Exchange邮件+附件代码

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2015-9-11 10:07:46 | 显示全部楼层 |阅读模式
          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[0].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[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.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[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),
                        "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[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;
                    ResponseStream.Close();
                    Response.Close();
                }
                return attach;
            }
            catch(Exception e)
            {
                return attach;
            }
        }


运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-112207-1-1.html 上篇帖子: HDU-1903 Exchange Rates 下篇帖子: 沟通无极限 Exchange Server 2007抢先体验
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表