C # Programming Guide (8) asynchronous C # send emails through GMAIL

Source: Internet
Author: User
Tags mailmessage smtpclient

 

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

 

 

 

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.