近日研究了下IBM Lotus Mail,這貨果然是麻煩,由於公司策略,沒有開放smtp,很多系統郵件都沒有辦法發送,於是入手google學習Lotus Mail,想做成Windows服務,提供wcf服務給內部應用系統使用。在google上找了很多資料,由於是系統郵件,很多東西配置起來又比較麻煩。自己也入了很多坑,特此作為記錄。廢話不多說,下面開始...
服務器環境:Windows Server 2008R2+Lotus Notes 8.5中文版
特別注意:Lotus Notes 8.5中文版需要配置好賬戶密碼,但是不需要打開它。
本地環境:Lotus Notes 8.5中文版+Visual Studio 2013
~~~~~~~~~~~~~~~~~~~~~~~我是優雅的分隔符~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1,打開VS,新建類庫項目LotusMailHelper,添加Lotus Domino Objects引用:
VS會自動編譯成dll
2,添加類Mail.cs,添加郵件發送方法SendMail:
/// <summary> /// 發送郵件 /// </summary> /// <param name="sendTo"></param> /// <param name="subject"></param> /// <param name="messageBody"></param> public bool SendMail(string[] sendTo, string subject, string messageBody)
3,在Mail.cs添加Using:using Domino;
4,編寫SendMail的邏輯
Domino.NotesSession nSession = new Domino.NotesSession();
string pwd = System.Configuration.ConfigurationManager.AppSettings["LotusMailPassword"];//lotus郵箱密碼
string server = System.Configuration.ConfigurationManager.AppSettings["LotusMailServer"];//lotus郵箱服務器地址
string serverPath = System.Configuration.ConfigurationManager.AppSettings["LotusMailServerPath"];//存儲nsf文件的路徑
string saveMessageOnSend = System.Configuration.ConfigurationManager.AppSettings["SaveMessageOnSend"];//發送前是否保存
nSession.Initialize(pwd);//初始化郵件
Domino.NotesDatabase nDatabase =
nSession.GetDatabase(server, serverPath, false);
Domino.NotesDocument nDocument = nDatabase.CreateDocument();
nDocument.ReplaceItemValue("SentTo", sendTo);//收件人,數據:數組
nDocument.ReplaceItemValue("Subject", subject);//主題
if (saveMessageOnSend == "1")//為1時保存到lotus的發件箱
{
nDocument.SaveMessageOnSend = true;
}
else
{
nDocument.SaveMessageOnSend = false;//設置保存與否
}
NotesStream HtmlBody = nSession.CreateStream();
HtmlBody.WriteText(messageBody);//構建HTML郵件,可以在頭和尾添加公司的logo和系統提醒語
NotesMIMEEntity mine = nDocument.CreateMIMEEntity("Body");//構建郵件正文
mine.SetContentFromText(HtmlBody, "text/html;charset=UTF-8", Domino.MIME_ENCODING.ENC_IDENTITY_BINARY);
nDocument.AppendItemValue("Principal", "XXX管理員");//設置郵件的發件人昵稱
nDocument.Send(false, sendTo); //發送郵件
nDocument.CloseMIMEEntities();//關閉
由於最後會封裝為dll,最好是添加try...catch...,加以優化,下面為優化過後:
/// <summary>
/// 發送lotus郵件(需要在web.config或者app.config中添加以下節點
///<appSettings>
/// <!--郵箱密碼-->
///<add key="LotusMailPassword" value="" />
/// <!--郵件服務器地址-->
///<add key="LotusMailServer" value="" />
/// <!--郵件數據庫路徑-->
///<add key="LotusMailServerPath" value="" />
/// <!--是否保存到發件箱(0不保存,1保存,其他值皆為不保存)-->
///<add key="SaveMessageOnSend" value="0" />
///</appSettings>
/// </summary>
/// <param name="sendTo">數組,收件人</param>
/// <param name="subject">主題</param>
/// <param name="messageBody">正文html</param>
/// <returns></returns>
public bool SendMail(string[] sendTo, string subject, string messageBody)
{
try
{
Domino.NotesSession nSession = new Domino.NotesSession();
string pwd = System.Configuration.ConfigurationManager.AppSettings["LotusMailPassword"];//lotus郵箱密碼
string server = System.Configuration.ConfigurationManager.AppSettings["LotusMailServer"];//lotus郵箱服務器地址
string serverPath = System.Configuration.ConfigurationManager.AppSettings["LotusMailServerPath"];//存儲nsf文件的路徑
string saveMessageOnSend = System.Configuration.ConfigurationManager.AppSettings["SaveMessageOnSend"];//發送前是否保存
nSession.Initialize(pwd);//初始化郵件
Domino.NotesDatabase nDatabase =
nSession.GetDatabase(server, serverPath, false);
Domino.NotesDocument nDocument = nDatabase.CreateDocument();
nDocument.ReplaceItemValue("SentTo", sendTo);//收件人,數據:數組
nDocument.ReplaceItemValue("Subject", subject);//主題
if (saveMessageOnSend == "1")//為1時保存到lotus的發件箱
{
nDocument.SaveMessageOnSend = true;
}
else
{
nDocument.SaveMessageOnSend = false;//設置保存與否
}
NotesStream HtmlBody = nSession.CreateStream();
HtmlBody.WriteText(messageBody);//構建HTML郵件,可以在頭和尾添加公司的logo和系統提醒語
NotesMIMEEntity mine = nDocument.CreateMIMEEntity("Body");//構建郵件正文
mine.SetContentFromText(HtmlBody, "text/html;charset=UTF-8", Domino.MIME_ENCODING.ENC_IDENTITY_BINARY);
nDocument.AppendItemValue("Principal", "XXX管理員");//設置郵件的發件人昵稱
nDocument.Send(false, sendTo); //發送郵件
nDocument.CloseMIMEEntities();//關閉
return true;//已經提交到lotus,返回true
}
catch
{
return false;//提交失敗
}
}
5,點擊項目生成,找到Bin文件夾中的dll,保存到自己喜歡的文件夾,方便後期的調用
============我是更加優美的分隔符=============
下面一起來建立Windows service
1,打開VS,新建Windows服務項目
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
}
OnStart:主要是寫入要啟動的邏輯代碼
OnStop:主要寫的是停止服務時要執行的方法,也就是邏輯代碼,我一般會將日志寫在這
2,將service1.cs刪除,新建一個Windows服務,並命名成公司要求的。例如我的是MailService.cs。
3,新建一個處理郵件的方法:
public void SendMail()
{
while(true)
{
//這裡寫郵件數據獲取以及發送郵件
Thread.Sleep(100);
}
}
4,構建郵件model:在解決方案點擊鼠標右鍵添加新建項目,選擇類庫項目,MailModel,新建MailInfo.cs
public class MailInfo
{
public string mailId { get; set; }
public string[] sendTo { get; set; }
public string subject { get; set; }
public string mailBody { get; set; }
}
5,新建類庫DbHelper,添加類Mail.cs,在裡面寫GetMailData()方法,RemoveMailData(),GetMailCount(),InsertMailData()等方法,這裡由於涉及到公司的信息,不是很方便寫出來。大家可以自行添加進去
public MailModel.MailInfo GetMailData()
{
//這裡寫獲取郵件數據
return MailInfo;//返回數據庫第一封待發郵件數據
}
public void RemoveMailData(string mailId)
{
//刪除數據庫中指定id的郵件數據
}
public long GetMailCount()
{
//這裡寫獲取郵件數量
return 郵件數量
}
public bool InsertMailData()
{
//這裡寫插入一封郵件數據
return true;
}
6,新建類庫WCF項目,添加wcf,名字為SendMail
// 注意: 使用“重構”菜單上的“重命名”命令,可以同時更改代碼和配置文件中的接口名“ISendMail”。
[ServiceContract]
public interface ISendMail
{
[OperationContract]
void DoWork();
}
裡面只有一個DoWork方法,我們新建一個ApplySendMail();注意:在頂上要添加[OperationContract]否則不會公開該函數。最後的ISendMail.cs代碼如下
[ServiceContract]
public interface ISendMail
{
[OperationContract]
string ApplySendMail(string[] sendTo, string subject, string body, string password);
}
接著打開SendMail.cs,去實現接口的ApplySendMail()方法
public class SendMail : ISendMail
{
public string ApplySendMail(string[] sendTo, string subject, string body, string password)
{
string result = string.Empty;
string mailPassword = System.Configuration.ConfigurationManager.AppSettings["password"];
if (mailPassword == password)
{
try
{
MailModel.MailInfo mail = new MailModel.MailInfo
{
sendTo = sendTo,
subject = subject,
mailBody = body
};
long count = DbHelper.Mail.GetMailCount();
if (DbHelper.Mail.InsertMailData(mail))
{
result = string.Format("提交成功.前面大約還有:{0}個任務", count);
}
return result;
}
catch
{
return "提交失敗";
}
}
else
{
return "密碼錯誤,無法提交";
}
}
}
至此wcf基礎已經可以了,下面繼續完成Windows服務那一塊
7,完成處理郵件的方法SendMail(),這裡要添加之前寫好的LoutusMailHelper.dll
public void SendMail()
{
while(true)
{
var mailData=DbHelper.Mail.GetMailData();
if(mailData!=null)
{
if(LotusMailHelper.Mail.SendMail(mailData.sendTo,mailData.subject,mailData.mailBody))
{
DbHelper.Mail.RemoveMailData(mailData.mailId);
}
Thread.Sleep(100);//休息0.1秒
}
else
{
Thread.Sleep(10000);//休息10秒鐘
}
}
}
8,完成OnStart()邏輯:①,先添加私有成員到MailService.cs
partial class MailService : ServiceBase
{
public MailService()
{
InitializeComponent();
}
private System.ServiceModel.ServiceHost _host;
/*
此處省略部分代碼
*/
}
②,編寫OnStart()代碼
protected override void OnStart(string[] args)
{
_host = new System.ServiceModel.ServiceHost(typeof(WCF.Mail));
_host.Open();
//啟動wcf服務
//啟動一個線程專門輪詢發送郵件
Thread sendMail = new Thread(new ThreadStart(SendMail));
sendMail.IsBackground = true;
sendMail.Start();
}
9,編寫OnStop()代碼,添加日志記錄代碼
10,配置App.config,wcf一定要配置。先看App.config中是否存在system.serviceModel節點,存在的話只需修改部分字段即可,不存在的話添加如下:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="WCF.Mail">
<endpoint address="" binding="basicHttpBinding" contract="WCF.IMail">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<!--wcf節點配置開始-->
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/MailService/Mail/" />
</baseAddresses>
</host>
<!--wcf節點配置結束-->
</service>
</services>
</system.serviceModel>
~~至此,基本的都已經完成,下面到Windows service部署
1,打開MailService.cs視圖界面,添加安裝程序。會自動出現如下界面:
***刪除服務:sc delete 服務名
至此,所有步驟都完成了,可以暢快的調用wcf來發送系統郵件了
<<<<<<<<<<<<<由於本人水平有限,可能存在很多錯誤,請諒解與批評指正>>>>>>>>>>>>>>
百度經驗 : C#創建Windows服務與安裝-圖解
推薦數據庫使用nosql數據庫,redis或者mongodb,在接下裡的隨筆裡我會記錄mongdb和redis的使用過程。。。第一次發文,緊張死寶寶了