16.7. Send SMTP Mail Using the SMTP Service
Problem
You want to be able to send email via SMTP from your program, but you don't want to learn the SMTP protocol and hand-code a class to implement it.
Solution
Use the System.Net.Mail namespace, which contains classes to take care of the harder parts of constructing an SMTP-based email message. The System.Net.Mail. MailMessage class encapsulates constructing an SMTP-based message, and the System.Net.Mail.SmtpClient class provides the sending mechanism for sending the message to an SMTP server. SmtpClient does depend on there being an SMTP server set up somewhere for it to relay messages through. Attachments are added by creating instances of System.Net.Mail.Attachment and providing the path to the file as well as the media type:
// Send a message with attachments string from = "hilyard@comcast.net"; string to = "hilyard@comcast.net"; MailMessage attachmentMessage = new MailMessage(from, to); attachmentMessage.Subject = "Hi there!"; attachmentMessage.Body = "Check out this cool code!"; // Many systems filter out HTML mail that is relayed attachmentMessage.IsBodyHtml = false; // Set up the attachment string pathToCode = @"..\..\16_Networking.cs"; Attachment attachment = new Attachment(pathToCode, MediaTypeNames.Application.Octet); attachmentMessage.Attachments.Add(attachment);
To send a simple email with no attachments, call the System.Net.Mail.MailMessage constructor with just the to, from, subject, and body information. This version of ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access