Some netizens asked me if I could send emails asynchronously. I have no problem in the test. Note that the SendCompleted event and SendAsync method are used here.
The Code is as follows. The code is simple and I don't know much about it.
1 using System;
2 using System. Collections. Generic;
3 using System. Linq;
4 using System. Text;
5 using System. Net;
6 using System. Net. Mail;
7 using System. Threading;
8
9 namespace MailTest
10 {
11 class Program
12 {
13 // block the thread.
14 private static AutoResetEvent _ event = new AutoResetEvent (false );
15
16 static void Main (string [] args)
17 {
18 string user = "zhangsan ";
19 string password = "zhangsan ";
20 //
21 string host = "smtp.gmail.com ";
22 //
23 string mailAddress = "zhangsan@gmail.com ";
24 string ToAddress = "zhangsan@hotmail.com ";
25 //
26
27 SmtpClient smtp = new SmtpClient (host );
28 smtp. EnableSsl = true; // enable the secure connection.
29 smtp. Credentials = new NetworkCredential (user, password); // create a user credential
30 smtp. DeliveryMethod = SmtpDeliveryMethod. Network; // use Network transfer
31 // create an email
32 MailMessage message = new MailMessage (mailAddress, ToAddress, "Test", "This is a Test Message ");
33 // register an event
34 smtp. SendCompleted + = new SendCompletedEventHandler (smtp_SendCompleted );
35 smtp. SendAsync (message, "TheObjectCompletedUse ");
36 // wait for completion.
37 _ event. WaitOne ();
38 Console. WriteLine ("Main method end ");
39}
40
41 private static void smtp_SendCompleted (object sender, System. ComponentModel. AsyncCompletedEventArgs e)
42 {
43 Console. WriteLine (string) e. UserState );
44 _ event. Set ();
45}
46}
47}
. It's easy. There is no problem in code testing. Be sure to replace it with a truly valid GMAIL account.
Download: Download