国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

C#WindowsService調用IBMLotusNotes發送郵件

2019-11-14 13:29:21
字體:
來源:轉載
供稿:網友

近日研究了下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服務項目

 名字隨便取。。。新建完成之后會自動生成Service1.cs,打開Service1.cs代碼看看,主要分為以下幾個方法:

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

添加完成之后VS會自動生成ISendMail.cs和SendMail.cs。打開ISendMail.cs會看到如下代碼

// 注意: 使用“重構”菜單上的“重命名”命令,可以同時更改代碼和配置文件中的接口名“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視圖界面,添加安裝程序。會自動出現如下界面:

選中serviceProcessInstaller1組件,查看屬性,設置account為LocalSystem

選中serviceInstaller1組件,查看屬性

設置ServiceName的值, 該值表示在系統服務中的名稱

設置StartType, 如果為Manual則手動啟動,默認停止,如果為Automatic為自動啟動

設置Description,添加服務描述

2,重新生成項目

3,打開Windows的cmd,輸入C:/Windows/Microsoft.NET/Framework/v4.0.30319/InstallUtil.exe exe路徑

等待安裝。安裝完畢之后打開計算機管理,查看服務,點擊啟動。

***刪除服務:sc delete 服務名

 

至此,所有步驟都完成了,可以暢快的調用wcf來發送系統郵件了

<<<<<<<<<<<<<由于本人水平有限,可能存在很多錯誤,請諒解與批評指正>>>>>>>>>>>>>>

 

 百度經驗 : C#創建Windows服務與安裝-圖解

 

推薦數據庫使用nosql數據庫,redis或者mongodb,在接下里的隨筆里我會記錄mongdb和redis的使用過程。。。第一次發文,緊張死寶寶了

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 云南省| 大田县| 屏东市| 梨树县| 安康市| 宝坻区| 琼中| 南充市| 津市市| 兰西县| 磴口县| 简阳市| 曲周县| 贵溪市| 岳池县| 黑河市| 象山县| 商丘市| 洪江市| 扎兰屯市| 闽侯县| 桐乡市| 文昌市| 苍南县| 吴旗县| 玉山县| 广灵县| 济源市| 盘锦市| 叙永县| 邳州市| 台山市| 镇赉县| 凤城市| 繁峙县| 浮山县| 浙江省| 铜川市| 秦皇岛市| 洛扎县| 白山市|