ProblemYou want to send an email automatically from your application without using an external application such as Outlook. SolutionSample code folder: Chapter 17\SendEmail Use the System.Net. Mail.SmtpClient class in the .NET Framework, supplying the server name and details specific to the email. DiscussionThe System.Net.Mail.SmtpClient class encapsulates an email submission. All you need to do is fill in its properties and call the Send() method, and your mail is delivered to the target recipient.
Create a new Windows Forms application, and add five TextBox controls named ServerHost, FromEmail, ToEmail, SubjectText, and BodyText. Set the BodyText control's Multiline property to true. Also add a Button control named ActSend, and set its Text property to Send. Add informational labels if desired. Your form should look something like Figure 17-11. Figure 17-11. Controls for the email-sending sampleNow add the following code to the form's class template: Imports System.Net.Mail Public Class Form1 Private Sub ActSend_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles ActSend.Click ' ----- Send the requested email. Dim emailSender As SmtpClient Dim theMessage As MailMessage ' ----- Connect to the server. A second optional ' argument lets you alter the port number from ' the default. emailSender = New System.Net.Mail.SmtpClient( _ ServerHost.Text) ' ----- Build the content details. theMessage = New MailMessage theMessage.From = New MailAddress(FromEmail.Text) theMessage.To.Add(ToEmail.Text) theMessage.Subject = SubjectText.Text theMessage.Body = BodyText.Text ' ----- Fill in the details and send. emailSender.Send(theMessage) End Sub End Class The MailMessage object includes properties that let you add attachments and specify the properties of the email message. Its To property is a collection that lets you add an unlimited number of email recipients. It also includes parallel CC and Bcc collections. |