My Development Notes

By Haemoglobin
3/10/2010 (revision 1)

Mail

MailMessage m = new MailMessage(to, from, subject, body); 

MailMessage m = new MailMessage(); 
m.From = new MailAddress(email, name); 
m.To.Add(new MailAddress(email, name)); 
m.Subject
m.Body // or use alternate views below

string html = @"";
string plainText = "Please choose a client that supports HTML emails"; 
AlternateView avHtml = AlternateView.CreateAlternateViewFromString(m.Body, null, MediaTypeNames.Text.Html); 
LinkedResource myPic = new LinkedResource("mypic.jpg", MediaTypeNames.Image.Jpeg);
myPic.ContentId = "MyPic"; 
avHtml.LinkedResources.Add(myPic); 

AlternateView avText = AlternateView.CreateAlternateViewFromString(plainText, null, MediaTypeNames.Text.Plain); 
m.AlternateViews.Add(avHtml); 
m.AlternateViews.Add(avText); 

m.Attachments.Add(new Attachment(@"c:\attachedfile.txt")); 
m.Attachments.Add(new Attachment(fileStream, fileName, MediaTypeNames.Application.Octet));
m.DeliveryNotificationOptions = NotificationOptions.OnSuccess|OnFailure|Delay|None|Never  //send to from address
m.ReplyTo
m.Priority = MailPriority.Normal|High|Low; 
m.IsBodyHtml = true; 

SmtpClient client  = new SmtpClient("smtp.server.com"); 
client.Credentials = CredentialCache.DefaultNetworkCredentials;
//or
client.UseDefaultCredentials = true; 
//or
client.Credentials = new NetworkCredential("user", "password"); 
client.EnableSsl = true; //not all smtp servers support this

try {
    client.Send(m); 
} catch (InvalidOperationException ex) {}
catch (SmtpFailedRecipientException ex) {} //only for addresses on local mail server, only in synchronous mode
catch (SmtpException ex) {} //If with inner WebException server hostname could not be found. Otherwise not a valid user or other transmission problems.

//Send asynchronously to avoid the system hanging when communcating to smtp server
static void SendCompleted(object sender, AsyncCompletedEventArgs e) {
    e.Cancelled
    if(e.Error != null) e.Error.ToString(); 
}

client.SendCompleted += new SendCompletedEventHandler(SendCompleted); 
client.SendAsync(m, null); 
client.SendAsyncCancel(); //usually user initiated

Comments

Powered by BlogEngine.NET 1.6.1.0 | Design by styleshout | Enhanced by GravityCube.net | 1.4.5 Changes by zembian.com | Adapted by HamishGraham.NET
(c) 2010 Hamish Graham. Banner Image (c) Chris Gin