In-depth explanation of how Lumisoft. NET implements the mail sending Function

Source: Internet
Author: User

In the previous articles, we have introduced the built-in SMTP mail sending function of DotNet, and the attachment and embedded image modes. This article continues to introduce Lumisoft. NET is a very good open-source component. Using this component to design and develop mail tools will become more convenient and powerful. Many articles on the Internet basically describe how to use this component to receive a large number of emails, but seldom describe how to use this component to send emails. This article mainly explores how to use this component to send emails. There are two ways to send Emails: one is to send emails without sending them, one is to use the sender account password and SMTP server to send emails. This article introduces these two methods respectively.

Components: http://www.lumisoft.ee/lswww/download/downloads/

Component Forum address: http://www.lumisoft.ee/Forum/default.aspx? G = forum

Adhering to the consistent practice, first post the relevant implementation graphics, sensory understanding, go to the detailed description, in order to achieve the best understanding depth.

1. First, set the sender. You can export text files and create new files to facilitate user operations.

2,The content can also be imported and exported and saved to the database for easy recording and operation. In addition, the content can be randomly obfuscated. The obfuscated content is hidden in HTML mail, it is easy to confuse server recognition.

3,You can select two email sending methods. The following describes the implementation of these two methods. One method uses this control to encapsulate a very good Direct Mail technology and does not need to be sent by an SMTP account; one is a common SMTP sending method. Of course, we can also set more parameters, such as mail tail information, HTML content prompts, and some settings for automatic dialing during sending.

4,Direct Mail technology attaches the user's email address (or can be disguised) by simulating an account ). I have filled in some frequently used SMTP server domain names to facilitate the construction of the required mail format, and can also set mail receipt notifications, as shown in.

5,If the common sending method is used, you need to specify the user's account password and other information. When sending the message, the system automatically obtains the sender information from the start for Batch Sending.

6,Finally, let's take a look at the sending effect of a small number of emails. Multiple Threads are used for sending. The famous SmartThreadPool component is used for multithreading. The sending process records the logs in detail for your reference.

After the related functions are introduced, we will analyze the code for implementing the main functions:

Copy codeThe Code is as follows: private TimerHelper timer = null;

Private void btnSend_Click (object sender, EventArgs e)
{
// Reset the counting variable
FailedItems = 0;
SuccessItems = 0;

WorkItemsCompleted = 0;
WorkItemsGenerated = 0;

Portal. gc. FailedCount = 0; // number of failed reset attempts

STPStartInfo stpStartInfo = new STPStartInfo ();
StpStartInfo. IdleTimeout = 10;
StpStartInfo. MaxWorkerThreads = 100;
StpStartInfo. MinWorkerThreads = 0;
// StpStartInfo. startsuincluded = true;
_ SmartThreadPool = new SmartThreadPool (stpStartInfo );
_ WorkItemsGroup = _ smartThreadPool;

WorkItemsProducerThread = new Thread (new ThreadStart (this. WorkItemsProducer ));
WorkItemsProducerThread. IsBackground = true;
WorkItemsProducerThread. Start ();

RefreshStatusCount ();

Int intervalRedial = SystemConfig. Default. IntervalRedial * 1000*60;
If (intervalRedial> 0)
{
If (timer! = Null)
{
Timer. Stop ();
Timer. Dispose ();
}
Timer = new TimerHelper (intervalRedial, false );
Timer. Execute + = new TimerHelper. TimerExecution (timer_Execute );
Timer. Start ();
}
}

Private static object locker = new object ();
Private void timer_Execute ()
{
If (Monitor. TryEnter (locker ))
{
String message = string. Format ("A Re-dialing operation was performed at {0} time! ", DateTime. Now );
ShowSendStatus (message );

String RasName = SystemConfig. Default. RasName;
If (! String. IsNullOrEmpty (RasName ))
{
Message = string. Format ("Preparing to re-dial ({0})", RasName );
ShowSendStatus (message );

Portal. gc. ReConnect (RasName );
Portal. gc. FailedCount = 0; // return to zero
}

Monitor. Exit (locker );
}
Else
{
Monitor. Enter (locker );
Monitor. Exit (locker );
}
}

The above are the main task generation operations and related dial-up operations. The detailed task Generation Code is as follows.
Private void WorkItemsProducer ()Copy codeThe Code is as follows :{
CallCtrlWithThreadSafetyEx.SetText(this.txt SendDetail ,"");

EnableControl (false, true, true );
String message = string. Format ("task start ");
RecordMessage (message );

# Region generation task

IWorkItemsGroup workItemsGroup = _ workItemsGroup;
If (null = workItemsGroup)
{
Return;
}

List <string> addressList = GetAddressList ();
List <MyMailInfo> mailInfoList = GetMailInfo ();
For (int I = 0; I <addressList. Count; I ++)
{
Try
{
SendJobInfo jobInfo = new SendJobInfo ();
JobInfo. domainList = mailDomainList;
JobInfo. mailTo = addressList [I];
JobInfo. mailInfo = GetOneMail (mailInfoList, I );
JobInfo. ShowSendStatus = ShowSendStatus;
JobInfo. currentDomain = (I % mailDomainList. Count); // sets a flag, which is sent by the account by default.
JobInfo. UseDirectSendType = SystemConfig. Default. EmailDirectSend;

// If the user does not specify the sending account, use the default display name
// If it is blank, the email address will be automatically used as the display name upon sending
If (string. IsNullOrEmpty (SystemConfig. Default. UserEmailFrom ))
{
JobInfo. mailFromDisplay = SystemConfig. Default. DefaultFromDisplayName;
}

WorkItemCallback = new WorkItemCallback (this. DoWork );
WorkItemsGroup. QueueWorkItem (workItemCallback, jobInfo );
Thread. Sleep (100 );
}
Catch (ObjectDisposedException ex)
{
LogTextHelper. WriteLine (ex. ToString ());
Continue;
}

Interlocked. Increment (ref workItemsGenerated );
}

# Endregion

RefreshStatusCount ();
Message = string. Format ("{0} tasks in total, {1} tasks remaining ",
WorkItemsGenerated, workItemsGenerated-workItemsCompleted );
CallCtrlWithThreadSafetyEx. SetText (this, message );
RecordMessage (message );

Try
{
// WorkItemsGroup. Start ();
WorkItemsGroup. WaitForIdle ();
_ SmartThreadPool. Shutdown ();
}
Catch (Exception ex)
{
LogTextHelper. WriteLine (ex. ToString ());
}

UpdateFinishStatus ();
}

Because multithreading is used for processing, you need to release the relevant thread objects when stopping sending, as shown in the following code.Copy codeThe Code is as follows: private void btnStop_Click (object sender, EventArgs e)
{
Try
{
_ SmartThreadPool. Shutdown ();
_ SmartThreadPool. Dispose ();
_ SmartThreadPool = null;

If (timer! = Null)
{
Timer. Stop ();
Timer. Dispose ();
}
}
Catch (Exception ex)
{
LogTextHelper. WriteLine (ex. ToString ());
}

UpdateFinishStatus ();
}

Specifically, the mail sending function is encapsulated in SendJobInfo, and different sending operations are performed by judging different types.

The most critical sending code is how to use LumiSoft. NET component to construct the corresponding mail object. The following describes the direct mail sending method first. Because this component is encapsulated well, the direct mail sending method is simple:

Copy codeThe Code is as follows: Mail_Message message = Create_PlainText_Html_Attachment_Image (mailTo, mailFrom, mailFromDisplay );
SMTP_Client.QuickSend (message );

The details of the Create_PlainText_Html_Attachment_Image encapsulation function are as follows:Copy codeThe Code is as follows:

Private Mail_Message Create_PlainText_Html_Attachment_Image (string mailTo, string mailFrom, string mailFromDisplay)
{
Mail_Message msg = new Mail_Message ();
Msg. MimeVersion = "1.0 ";
Msg. MessageID = MIME_Utils.CreateMessageID ();
Msg. Date = DateTime. Now;
Msg. From = new Mail_t_MailboxList ();
Msg. From. Add (new Mail_t_Mailbox (mailFromDisplay, mailFrom ));
Msg. To = new Mail_t_AddressList ();
Msg. To. Add (new Mail_t_Mailbox (mailTo, mailTo ));
Msg. Subject = mailInfo. Title;

// Set the receipt notification
String paiyemail = SystemConfig. Default. DispositionNotificationTo;
If (! String. IsNullOrEmpty (receivyemail) & ValidateUtil. IsEmail (receivyemail ))
{
Msg. DispositionNotificationTo = new Mail_t_Mailbox (yemail, yemail );
}

# Region MyRegion
// --- Multipart/mixed -----------------------------------
MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType (MIME_MediaTypes.Multipart.mixed );
ContentType_multipartMixed.Param_Boundary = Guid. NewGuid (). ToString (). Replace ('-','.');
MIME_ B _MultipartMixed multipartMixed = new MIME_ B _MultipartMixed (contentType_multipartMixed );
Msg. Body = multipartMixed;

// --- Multipart/alternative -----------------------------
MIME_Entity entity_multipartAlternative = new MIME_Entity ();
MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType (MIME_MediaTypes.Multipart.alternative );
ContentType_multipartAlternative.Param_Boundary = Guid. NewGuid (). ToString (). Replace ('-','.');
MIME_ B _MultipartAlternative multipartAlternative = new MIME_ B _MultipartAlternative (contentType_multipartAlternative );
Entity_multipartAlternative.Body = multipartAlternative;
MultipartMixed. BodyParts. Add (entity_multipartAlternative );

// --- Text/plain ----------------------------------------
MIME_Entity entity_text_plain = new MIME_Entity ();
MIME_ B _Text text_plain = new MIME_ B _Text (MIME_MediaTypes.Text.plain );
Entity_text_plain.Body = text_plain;

// The content of a common text email. This is required if the recipient's receiving client does not support HTML.
String plainTextBody = "If your mail client does not support HTML format, or you switch to the" common text "view, you will see this content ";
If (! String. IsNullOrEmpty (SystemConfig. Default. PlaintTextTips ))
{
PlainTextBody = SystemConfig. Default. PlaintTextTips;
}

Text_plain.SetText (MIME_TransferEncodings.QuotedPrintable, Encoding. UTF8, plainTextBody );
MultipartAlternative. BodyParts. Add (entity_text_plain );

// --- Text/html -----------------------------------------
String htmlText = mailInfo. content; // "MIME_Entity entity_text_html = new MIME_Entity ();
MIME_ B _Text text_html = new MIME_ B _Text(MIME_MediaTypes.Text.html );
Entity_text_html.Body = text_html;
Text_html.SetText (MIME_TransferEncodings.QuotedPrintable, Encoding. UTF8, htmlText );
MultipartAlternative. BodyParts. Add (entity_text_html );

// --- Application/octet-stream -------------------------
Foreach (string attach in mailInfo. Attachments)
{
MultipartMixed. BodyParts. Add (Mail_Message.CreateAttachment (attach ));
}

Foreach (string imageFile in mailInfo. EmbedImages)
{
MIME_Entity entity_image = new MIME_Entity ();
Entity_image.ContentDisposition = new MIME_h_ContentDisposition (MIME_DispositionTypes.Inline );
String fileName = DirectoryUtil. GetFileName (imageFile, true );
Entity_image.ContentID = BytesTools. BytesToHex (Encoding. Default. GetBytes (fileName ));
MIME_ B _Image body_image = new MIME_ B _Image(MIME_MediaTypes.Image.jpeg );
Entity_image.Body = body_image;
Body_image.SetDataFromFile (imageFile, MIME_TransferEncodings.Base64 );
MultipartMixed. BodyParts. Add (entity_image );
}

# Endregion

Return msg;
}

If you use a common account to send SMTP mail, the main code is as follows. It can be seen that commands are used to interact with the server step by step.Copy codeThe Code is as follows: using (SMTP_Client client = new SMTP_Client ())
{
Int port = domainInfo. Ssl? WellKnownPorts. SMTP_SSL: WellKnownPorts. SMTP;
If (domainInfo. Port> 0)
{
Port = domainInfo. Port;
}

Client. Connect (domainInfo. SmtpServer, port, domainInfo. Ssl );
Client. Authenticate (domainInfo. Username, domainInfo. Password );
// String text = client. GreetingText;
Client. MailFrom (mailFrom,-1 );
Client. rcp.pdf (mailTo );

MemoryStream stream = Create_Html_Attachment_Image (mailTo, mailFrom, mailFromDisplay );
Client. SendMessage (stream );
Client. Disconnect ();
}

The code for constructing the mail content is similar to that of the previous section. The detailed code is as follows.Copy codeThe Code is as follows: private MemoryStream Create_Html_Attachment_Image (string mailTo, string mailFrom, string mailFromDisplay)
{
Mime m = new Mime ();
MimeEntity mainEntity = m. MainEntity;

MainEntity. From = new AddressList ();
MainEntity. From. Add (new MailboxAddress (mailFromDisplay, mailFrom ));

MainEntity. To = new AddressList ();
MainEntity. To. Add (new MailboxAddress (mailTo, mailTo ));
MainEntity. Subject = mailInfo. Title;
MainEntity. ContentType = MediaType_enum.Multipart_mixed;

MimeEntity textEntity = mainEntity. ChildEntities. Add ();
TextEntity. ContentType = MediaType_enum.Text_html;
TextEntity. ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable;
TextEntity. DataText = mailInfo. Content;
.........................

MemoryStream msg = new MemoryStream ();
M. ToStream (msg );
Msg. Position = 0;

Return msg;
}

Use Lumisoft. the. NET component can implement a lot of related mail operations. Here, it is for interest and space reasons. It mainly introduces the function module of mail sending, in which the code is pasted, one is to communicate with interested friends, and the other is to learn from them in the future. It does not encourage everyone to use this software or code to send spam in large batches.

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.