6

【程式範例】使用Gmail IMAP讀取信件

 3 years ago
source link: https://blog.darkthread.net/blog/gmail-imap-sample/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

【程式範例】使用Gmail IMAP讀取信件

2011-01-18 05:59 AM 26 27,528

工作上有從Gmail讀信取出附檔的需求,先前在點部落上看過不少用Gmail SMTP送信的範例(by 艾小克dotjum),但一直沒看到讀信範例,在網路爬文也只陸續看到一些片斷,經過一番嘗試,總算拼湊出完整的收信並移至垃圾桶程式範例,特此分享。

關於收信功能,Gmail提供了POP3及IMAP兩種收信協定[補充],POP3較簡陋,只提供讓你將信全部抓回家的基本功能;而IMAP則還能支援讀取不同信件匣、設定"已閱讀"、移動信件到其他資料夾... 等功能,操作結果從Gmail網頁介面也看得到,已有幾分Gmail API的味道。因此,就決定使用較先進的IMAP協定與Gmail溝通。

目前已找得到不少使用.NET實作IMAP協定的元件或程式庫(免費跟收錢的都有),但由於Gmail IMAP一律要走SSL,並不是全部元件都支援的。評估之後,決定使用CodePlex上的Open Source專案--MailSystem.NET

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

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

排版顯示純文字
        static void Main(string[] args)
        {
            Imap4Client clnt = new Imap4Client();
            //使用ConnectSsl進行加密連線
            var hmm = clnt.ConnectSsl("imap.gmail.com", 993);
            //登入
            clnt.Login("[email protected]", "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;
        }

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK