System.Net.Mail 异步发送邮件
1
using System;2
using System.Net;3
using System.Net.Mail;4
using System.Net.Mime;5
using System.Threading;6
using System.ComponentModel;7
namespace Examples.SmptExamples.Async8


{9
public class SimpleAsynchronousExample10

{11
static bool mailSent = false;12
public static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)13

{14
// Get the unique identifier for this asynchronous operation.15
String token = (string) e.UserState;16
17
if (e.Cancelled)18

{19
Console.WriteLine("[{0}] Send canceled.", token);20
}21
if (e.Error != null)22

{23
Console.WriteLine("[{0}] {1}", token, e.Error.ToString());24
} else25

{26
Console.WriteLine("Message sent.");27
}28
mailSent = true;29
}30
public static void Main(string[] args)31

{32
// Command line argument must the the SMTP host.33
SmtpClient client = new SmtpClient(args[0]);34
// Specify the e-mail sender.35
// Create a mailing address that includes a UTF8 character36
// in the display name.37
MailAddress from = new MailAddress("jane@contoso.com", 38
"Jane " + (char)0xD8+ " Clayton", 39
System.Text.Encoding.UTF8);40
// Set destinations for the e-mail message.41
MailAddress to = new MailAddress("ben@contoso.com");42
// Specify the message content.43
MailMessage message = new MailMessage(from, to);44
message.Body = "This is a test e-mail message sent by an application. ";45
// Include some non-ASCII characters in body and subject.46

string someArrows = new string(new char[]
{'\u2190', '\u2191', '\u2192', '\u2193'});47
message.Body += Environment.NewLine + someArrows;48
message.BodyEncoding = System.Text.Encoding.UTF8;49
message.Subject = "test message 1" + someArrows;50
message.SubjectEncoding = System.Text.Encoding.UTF8;51
// Set the method that is called back when the send operation ends.52
client.SendCompleted += new 53
SendCompletedEventHandler(SendCompletedCallback);54
// The userState can be any object that allows your callback 55
// method to identify this send operation.56
// For this example, the userToken is a string constant.57
string userState = "test message1";58
client.SendAsync(message, userState);59
Console.WriteLine("Sending message
press c to cancel mail. Press any other key to exit.");60
string answer = Console.ReadLine();61
// If the user canceled the send, and mail hasn't been sent yet,62
// then cancel the pending operation.63
if (answer.StartsWith("c") && mailSent == false)64

{65
client.SendAsyncCancel();66
}67
// Clean up.68
message.Dispose();69
Console.WriteLine("Goodbye.");70
}71
}72
}

浙公网安备 33010602011771号