1. 程式人生 > 其它 >C# 讀取指定郵箱的郵件,並自動建立工單

C# 讀取指定郵箱的郵件,並自動建立工單

設計思路

1. 寫一個郵件服務配置介面,主要包括郵件地址(Email),協議(Protocol),郵件伺服器的地址(Email Server),密碼(Password),埠(Port),是否使用SSL等。

2. 寫windows service程式,定時(通常每小時執行一次)執行一段程式。這段程式首先讀取郵件服務配置,然後通過EAGetMail(第三方類庫)連線上郵件伺服器,讀取郵箱中未讀郵件(對於非pop3協議) ,根據郵件內容建立工單,最後標記郵件已讀或者刪除郵件。

通過EAGetMail(第三方類庫)讀取郵件的示例程式碼

using System;
using System.Globalization;
using System.IO; using EAGetMail; //add EAGetMail namespace namespace receiveemail { class Program { // Generate an unqiue email file name based on date time static string _generateFileName(int sequence) { DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml", currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")), currentDateTime.Millisecond, sequence); } static void Main(string[] args) { try {
// Create a folder named "inbox" under current directory // to save the email retrieved. string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory()); // If the folder is not existed, create it. if (!Directory.Exists(localInbox)) { Directory.CreateDirectory(localInbox); } MailServer oServer = new MailServer("imap.emailarchitect.net", "[email protected]", "testpassword", ServerProtocol.Imap4); // Enable SSL/TLS connection, most modern email server require SSL/TLS by default oServer.SSLConnection = true; oServer.Port = 993; // if your server doesn't support SSL/TLS, please use the following codes // oServer.SSLConnection = false; // oServer.Port = 143; MailClient oClient = new MailClient("TryIt"); oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); Console.WriteLine("Total {0} email(s)\r\n", infos.Length); for (int i = 0; i < infos.Length; i++) { MailInfo info = infos[i]; Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", info.Index, info.Size, info.UIDL); // Receive email from IMAP4 server Mail oMail = oClient.GetMail(info); Console.WriteLine("From: {0}", oMail.From.ToString()); Console.WriteLine("Subject: {0}\r\n", oMail.Subject); // Generate an unqiue email file name based on date time. string fileName = _generateFileName(i + 1); string fullPath = string.Format("{0}\\{1}", localInbox, fileName); // Save email to local disk oMail.SaveAs(fullPath, true); // Mark email as deleted from IMAP4 server. oClient.Delete(info); } // Quit and expunge emails marked as deleted from IMAP4 server. oClient.Quit(); Console.WriteLine("Completed!"); } catch (Exception ep) { Console.WriteLine(ep.Message); } } } }

讀取郵件常用埠

郵件協議 常用埠 SSL埠
Imap4
143
993
Pop3
110
995