Next we design our mail application by placing textboxes for From, To, Copy, Blind Copy, Subject, Attachment, and the Message Body. We then add corresponding labels for each of the textboxes. Also, we add a button for sending the message and a button to exit the application. As an added feature, we placed a browse button next to the attachment so we can browse for attachments on our file system. The browse button uses the OpenFileDialog component for navigating for an attachment (as seen at the bottom of the designer.)
Figure 5 - E-Mail Sender Design View
Below is the code used to send the email we construct in our form. The code is executed in the SendButton_Click Event Handler. The method simply creates a new MailMessage instance and populates it with the text typed into the various fields by the user. The MailMessage object is then sent using the SmtpMail.Send static function:
Listing 2 - Send Button Event Handler
private
void
SendButton_Click(object sender, System.EventArgs
e)
|
Below is the button event handler for populating the Attachment
field through the Browse button.
It simply calls ShowDialog on the OpenFileDialog instance and if the result is
ok it assigns the filename chosen by the user to the attachment field:
Listing 3 - Browse Button Event Handler
private
void
BrowseButton_Click(object sender, System.EventArgs
e)
|
I suspect you'd be more likely to use Microsoft Outlook then this simple application, but you can utilize the code in this application to customize it to suit your specific needs. For example, you might consider creating a database in access and writing C# and ADO.NET for accessing groups of people you'd like to send emails. You could change this into a component and have it pop up when you need to send emails in your application. In any case, this will get you started in your quest to send emails using .NET.
Comments