C # Windows Service calls IBM Lotus Notes to send an email,

Source: Internet
Author: User

C # Windows Service calls IBM Lotus Notes to send an email,

I recently studied IBM Lotus Mail, which is really troublesome. Due to the company's policy, smtp is not enabled, and many system emails cannot be sent. So I started to learn about Lotus Mail by google, to create a Windows service, provide the wcf Service for internal application systems. I found a lot of information on google, because it is a system email, many things are difficult to configure. I have entered a lot of pitfalls, and I would like to record them here. Not much nonsense. Let's start...

Server Environment: Windows Server 2008R2 + Lotus Notes 8.5 Chinese Version

Note: you do not need to enable the account password for the Chinese version of Lotus Notes 8.5.

Local Environment: Lotus Notes 8.5 Chinese version + Visual Studio 2013

~~~~~~~~~~~~~~~~~~~~~~~ I am an elegant separator ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

1. Open VS, create the LotusMailHelper class library project, and add the Lotus Domino Objects Reference:

VS is automatically compiled into a dll.

2. Add Mail. cs class and add the Mail sending method SendMail:

/// <Summary> /// send the email /// </summary> /// <param name = "sendTo"> </param> /// <param name = "subject"> </param> // <param name = "messageBody"> </param> public bool SendMail (string [] sendTo, string subject, string messageBody)

3. Add Using: using Domino in Mail. cs;

4. Write the SendMail Logic

Domino. notesSession nSession = new Domino. notesSession (); string pwd = System. configuration. configurationManager. appSettings ["LotusMailPassword"]; // lotus mailbox password string server = System. configuration. configurationManager. appSettings ["LotusMailServer"]; // address of the lotus mailbox Server string serverPath = System. configuration. configurationManager. appSettings ["LotusMailServerPath"]; // path for nsf file storage string saveMessageOnSend = System. configuration. configurationManager. deleetask[ "SaveMessageOnSend"]; // whether to save nSession before sending. initialize (pwd); // Initialize the mail Domino. notesDatabase nDatabase = nSession. getDatabase (server, serverPath, false); Domino. notesDocument nDocument = nDatabase. createDocument (); nDocument. replaceItemValue ("SentTo", sendTo); // recipient, data: array nDocument. replaceItemValue ("Subject", subject); // when the topic if (saveMessageOnSend = "1") // is 1, it is saved to the sender {nDocument of lotus. saveMessageOnSend = true;} else {nDocument. saveMessageOnSend = false; // set whether to save} NotesStream HtmlBody = nSession. createStream (); HtmlBody. writeText (messageBody); // construct an HTML email. You can add the company logo and system reminder NotesMIMEEntity mine = nDocument at the beginning and end. createMIMEEntity ("Body"); // construct the mail Body mine. setContentFromText (HtmlBody, "text/html; charsets = UTF-8", Domino. MIME_ENCODING.ENC_IDENTITY_BINARY); nDocument. appendItemValue ("Principal", "XXX administrator"); // set the sender nickname of the email to nDocument. send (false, sendTo); // Send the mail nDocument. closeMIMEEntities (); // close

Since it will be encapsulated as dll at last, it is best to add try... catch... to optimize it. The following figure shows the optimization:

/// <Summary> /// send a lotus producer (you need to add the following endpoints in web. config or app. config /// <deleteapps>// <! -- Binning password --> // <add key = "LotusMailPassword" value = "/> /// <! -- Courier server address --> // <add key = "LotusMailServer" value = "/> /// <! -- Component data cannot be stored. --> // <add key = "LotusMailServerPath" value = ""/> /// <! -- Whether to save to the sending box (0 is not saved, 1 is saved, and other values are not saved) --> /// <add key = "SaveMessageOnSend" value = "0"/> /// </receivetask>/// </summary> // <param name = "sendTo"> Data Group, recipient </param> /// <param name = "subject"> subject </param> /// <param name = "messageBody"> body 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 mailbox password string server = System. configuration. configurationManager. appSettings ["LotusMailServer"]; // address of the lotus mailbox Server string serverPath = System. configuration. configurationManager. appSettings ["LotusMailServerPath"]; // path for nsf file storage string saveMessageOnSend = System. configuration. configurationManager. deleetask[ "SaveMessageOnSend"]; // whether to save nSession before sending. initialize (pwd); // Initialize the mail Domino. notesDatabase nDatabase = nSession. getDatabase (server, serverPath, false); Domino. notesDocument nDocument = nDatabase. createDocument (); nDocument. replaceItemValue ("SentTo", sendTo); // recipient, data: array nDocument. replaceItemValue ("Subject", subject); // when the topic if (saveMessageOnSend = "1") // is 1, it is saved to the sender {nDocument of lotus. saveMessageOnSend = true;} else {nDocument. saveMessageOnSend = false; // set whether to save} NotesStream HtmlBody = nSession. createStream (); HtmlBody. writeText (messageBody); // construct an HTML email. You can add the company logo and system reminder NotesMIMEEntity mine = nDocument at the beginning and end. createMIMEEntity ("Body"); // construct the mail Body mine. setContentFromText (HtmlBody, "text/html; charsets = UTF-8", Domino. MIME_ENCODING.ENC_IDENTITY_BINARY); nDocument. appendItemValue ("Principal", "XXX administrator"); // set the sender nickname of the email to nDocument. send (false, sendTo); // Send the mail nDocument. closeMIMEEntities (); // close return true; // has been submitted to lotus, return true} catch {return false; // submit Failed }}

5. Click project generation, find the dll in the Bin folder, and save it to your favorite folder for later calls.

=============== I am a more beautiful separator ====================

Next we will create a Windows service

1. Open VS and create a Windows service project.

Public partial class Service1: ServiceBase {public Service1 () {InitializeComponent ();} protected override void OnStart (string [] args) {} protected override void OnStop (){}}

OnStart: Write the logical code to be started.
OnStop: mainly describes the method to be executed when the service is stopped, that is, the logic code.

2. Delete service1.cs, create a new Windows service, and name it as required by the Company. For example, my account is MailService. cs.

3. Create a new mail processing method:

Public void SendMail () {while (true) {// write the email data here to get and send the email Thread. Sleep (100 );}}

4. Create mail model: Right-click solution to add a new project, select a class library project, MailModel, and create 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. Create a new class library DbHelper and add Mail class. cs: Write the GetMailData () method, RemoveMailData (), GetMailCount (), InsertMailData () and other methods in it. It is not convenient to write the information about the company. You can add them on your own.

Public MailModel. mailInfo GetMailData () {// write here to get mail data return MailInfo; // return the first mail data in the database} public void RemoveMailData (string mailId) {// Delete the email data of the specified id in the database} public long GetMailCount () {// here write get mail count return mail count} public bool InsertMailData () {// insert an email data here return true ;}

6. Create a class library WCF project and add a wcf named SendMail.

// Note: You can use the "RENAME" command on the "refactoring" menu to change the Interface Name "ISendMail" in the Code and configuration file at the same time ". [ServiceContract] public interface ISendMail {[OperationContract] void DoWork ();}

There is only one DoWork method in it. We create a new ApplySendMail (). Note: Add [OperationContract] on the top; otherwise, this function will not be published. The final ISendMail. cs code is as follows:

[ServiceContract]public interface ISendMail{    [OperationContract]    string ApplySendMail(string[] sendTo, string subject, string body, string password);}

Enable SendMail. cs to implement the ApplySendMail () method of the interface.

Public class SendMail: ISendMail {public string ApplySendMail (string [] sendTo, string subject, string body, string password) {string result = string. empty; string mailPassword = System. configuration. configurationManager. deleetask[ "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 ("submitted successfully. previous conventions also include: {0} Tasks ", count);} return result;} catch {return" ";}} else {return" Incorrect password, unable to submit ";}}}

Now that the wcf foundation is ready, we can continue to complete the Windows Service Section.

7. Complete the mail processing method SendMail (). Add the previously written LoutusMailHelper. dll here.

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); // rest for 0.1 seconds} else {Thread. sleep (10000); // 10 seconds to rest }}}

8. Complete the OnStart () logic: ① Add a private member to MailService. cs first.

Partial class MailService: ServiceBase {public MailService () {InitializeComponent ();} private System. ServiceModel. ServiceHost _ host;/* some code is omitted here */}

② Compile OnStart () Code

Protected override void OnStart (string [] args) {_ host = new System. serviceModel. serviceHost (typeof (WCF. mail); _ host. open (); // start the wcf Service // start a Thread to specifically poll and send the mail Thread sendMail = new Thread (new ThreadStart (SendMail); sendMail. isBackground = true; sendMail. start ();}

9. Write the OnStop () Code and add the logging code.

10. Configure App. config. Ensure that wcf is configured. Check whether the system. serviceModel node exists in App. config. If it exists, modify some fields. If it does not exist, add the following:

<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> </endpo Int> <endpoint address = "mex" binding = "mexHttpBinding" contract = "IMetadataExchange"/> <! -- Start the wcf node configuration --> 

~~ At this point, the basic information has been completed, and the Windows service is deployed below.

1. Open the MailService. cs view and add the installer. The following page is automatically displayed:

* ** Delete service: SC delete service name

 

So far, all the steps have been completed. You can call wcf to send system emails with ease.

<I may encounter many errors due to my limited level, please forgive and criticize >>>>>>>>>>>>>>>>>

 

Baidu experience:C # create a Windows Service and install it-Diagram

 

We recommend that you use nosql databases, redis or mongodb. In the next article, I will record the usage of mongdb and redis... The first time I published this article, I got nervous about my baby.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.