Recipe 17.9. Sending Email Using SMTP


Problem

You want to send an email automatically from your application without using an external application such as Outlook.

Solution

Sample 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.

Discussion

The 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.

To send email, you must have authorized access to an SMTP server.


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 sample


Now 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.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net