zoukankan      html  css  js  c++  java
  • MailSystem.NET Gmail IMAP讀取信件

    程式的主流程為: 開啟SSL連線,逐一讀取收信匣中的信件,將信件內文HTML及附檔逐一存檔後,再將信件移至垃圾桶。

    程式碼如下,補充說明我寫在註解裡,請參考:

            static void Main(string[] args)
    
            {
    
                Imap4Client clnt = new Imap4Client();
    
                //使用ConnectSsl進行加密連線
    
                var hmm = clnt.ConnectSsl("imap.gmail.com", 993);
    
                //登入
    
                clnt.Login("blahblah@gmail.com", "blahblah");
    
                //取得收件匣
    
                Mailbox inbox = clnt.SelectMailbox("inbox");
    
                //因讀完信就會移至垃圾桶,故由後讀到前,以免序號變動
    
                for (int n = inbox.MessageCount; n > 0; n--)
    
                {
    
                    //取回第n封信
    
                    ActiveUp.Net.Mail.Message m = inbox.Fetch.MessageObject(n);
    
                    //為每封郵件建立專屬資料夾(要換掉主旨不能當資料夾名稱的字元)
    
                    string msgFolder = string.Format("{0:yyyyMMddHHmmsss}-{1}", 
    
                        m.ReceivedDate, ReplaceInvalidPathChars(m.Subject));
    
                    if (!Directory.Exists(msgFolder))
    
                        Directory.CreateDirectory(msgFolder);
    
                    //將信件內文(HTML)寫入MailBody檔案
    
                    string f = Path.Combine(msgFolder, "MailBody.html");
    
                    File.WriteAllText(f, m.BodyHtml.Text);
    
                    //逐一寫入附件檔案
    
                    foreach (MimePart att in m.Attachments)
    
                    {
    
                        f = Path.Combine(msgFolder,
    
                            //換掉不能當檔案名的字元
    
                            ReplaceInvalidFileNameChars(att.Filename));
    
                        File.WriteAllBytes(f, att.BinaryContent);
    
                    }
    
                    //將信件移至垃圾桶(CopyMessage即可產生移動資料夾的效果)
    
                    inbox.CopyMessage(n, "[Gmail]/Trash");
    
                    Console.WriteLine("{0}.{1}", n, m.Subject);
    
                }
    
                Console.Read();
    
            }
    
            //將不可做為路徑名稱的字元換成_
    
            static string ReplaceInvalidPathChars(string raw)
    
            {
    
                foreach (char c in Path.GetInvalidPathChars())
    
                    raw = raw.Replace(c, '_');
    
                return raw;
    
            }
    
            //將不可做為檔案名稱的字元換成_
    
            static string ReplaceInvalidFileNameChars(string raw)
    
            {
    
                foreach (char c in Path.GetInvalidFileNameChars())
    
                    raw = raw.Replace(c, '_');
    
                return raw;
    
            }
  • 相关阅读:
    gulp通过http-proxy-middleware开启反向代理,实现跨域
    一些我常用的css 或者 js
    四舍五入
    生成 SSH 公钥
    对象转为数组 用lodash
    廖雪峰的官方网站
    window对象
    字符串
    简单得日期
    LeetCode 113. Path Sum II 20170705 部分之前做了没写的题目
  • 原文地址:https://www.cnblogs.com/zeroone/p/3299250.html
Copyright © 2011-2022 走看看