Lesson 1: Creating mail message
At its simplest email message has sender, recipient, subject and body. Can be created with single line of code. At most complex can have custom encoding types,multiple views for plain and html text, attachments and embedded images.
Creating and sending message
Crete System.Net.Mail.MailMessage object. This has four constructors - creating of blank message, or specify sender, recipient, subject and body
MailMessage m = new MailMessage ("firstname.lastname@example.org", "email@example.com", "Quarterly report", "See attached spreadsheet");
If did not specify recipients when creating MailMessage object, then add them to MailMessage object. If need to specify multiple recipients then create blank MailMessage and add multiple MailAddress objects.
MailMessage m = new MailMessage(); m.From = new MailAddress("firstname.lastname@example.org", "Lance Tucker"); m.To.Add(new MailAddress("email@example.com", "James Eaton")); m.To.Add(new MailAddress("firstname.lastname@example.org", "Ben Miller")); m.To.Add(new MailAddress("email@example.com", "Burke Fewel")); m.Subject = "Quarterly report"; m.Body = "See attached spreadsheet";
If multiple view required then create AlternateView objects and add to MailMessage
If required create one or more Attachment objects and add to MailMessage. Simplest way to add file is to call Addoverride of Attachmentthat takes a file name. Other overrides allow MIME type to be specified, e.g.
MailMessage m = new MailMessage(); Stream sr = new FileStream (@"C:\boot.ini", FileMode.Open, FileAccess.Read); m.Attachments.Add(sr, "myfile.txt", MediaTypeNames.Application.Octet);
Create SmtpClient object and specify SMTP server.
If the SMTP server requires authentication credentials then add to SmtpClient object.
Pass MailMessage object to SmtpClient.Send method.
Can also use Cc and Bcc fields of the MessageBody to send copies. Care should be taken with the Bcc field as spam filters will frequently block messages that do not have the recipients address in the To header.
MailMessage also has less frequently used properties
- DeliveryNotificationOptions - instructs SMTP server to send message in MailMessage.From if message is delayed, fails, successfully delivered or relayed. The enumeration takes the values OnSuccess, OnFailure, Delay, None and Never.
- ReplyTo - address that replies will be sent to
- Priority - does not affect how framework or mail server handles message. Priority may be visible in recipients email client. Enumeration has values Normal, High and Low.
Create HTML Emails
Supply HTML tagged content in MailMessage.Body and set MailMessage.IsBodyHtml attribute to true.
To embed images use AlternateView and LinkedResource classes.
To reference images in the HTML message body use "cid:contentID" in the< img> tag where the contentID matches the name given to the LinkedResource.
Lesson 2: Sending Mail
In .NET framework the SmtpClient class represents the SMTP server used to send messages.
MailMessage m = new MailMessage ("firstname.lastname@example.org", "email@example.com", "Quarterly report", "See attached spreadsheet"); SmtpClient client = new SmtpClient("smtp.contoso.com"_; client.Send(m);
Handling Mail Exceptions
Many things can go wrong when sending email message, e.g. mail server is not available, it may reject authentication credentials, a recipient may be invalid, etc. The runtime will throw an exception that the application must handle.
Should catch SmtpException that is raised when server cannot be found, the message is identified as spam or authentication has failed.
Should catch SmtpFailedRecipientException raised if the server rejects a recipient email address. SMTP servers will only reject local recipients.
Some SMTP server determine authorisation based on clients IP address. Others require users to provide a valid user name and password.
To use default credentials set SmtpClient.UseDefaultCredentials to true. Alternatively, set SmtpClient.Credentials to CredentialCache.DefaultNetworkCredentials. To specify a user name and password create an instance of System.Net.NetworkCredential and set SmtpClient.Credentials to it.
SmtpClient client = new SmtpClient("smtp.contoso.com"); client.Credentials = new NetworkCredential("user", "password");
Always enable SSL support if the SMTP server supports it, by setting SmtpClient.EnableSsl to true.
Sending email can be slow. Sometimes the server can be completely unresponsive, causing application to wait for the value specified in SmtpClient.Timeout. To send asyncrhonously perform these tasks:
- Create method to respond to SmtpClient.SendCompleted event. This needs to determine if transmission was successful, unsuccessful or cancelled.
- Add your event handler to SmtpClient.SendCompleted
- Call SmtpClient.SendAsync
- Optionally, provide user opportunity to cancel sending email by calling SmtpClient.SendAsyncCancel