Requirements to send Email in .NET
1. We need to reference the System.Net.Mail namespace to create and send email messages.
Use it on VB.NET
Or in C#
2. We need a relay server to send email through. A relay server is a mail server, or a SMTP server/service, that can handle sending email. System.Net.Mail sends the mail to a relay server, and the relay server is responsible for delivering it to the recipient's mail server.
Sample code of sending plain text using VB.NET
'create the mail message
Dim mail As New MailMessage()
'set the addresses
mail.From = New MailAddress("email@example.com")
'set the content
mail.Subject = "This is an email"
mail.Body = "this is a sample body"
'send the message
Dim smtp As New SmtpClient("127.0.0.1")
Sample code of sending plain text using C#
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("firstname.lastname@example.org");
//set the content
mail.Subject = "This is an email";
mail.Body = "this is a sample body";
//send the message
SmtpClient smtp = new SmtpClient("127.0.0.1");
To send an email in HTML format, just add set the isBodyHtml property to true of the MailMessage object. After setting it, you can already include HTML tags inside the Body property.
'set the content to HTML
mail.IsBodyHtml = true
//set the content to HTML
mail.IsBodyHtml = true;
To add an attachment on your email, make use of the Attachements property as shown below.
Email Attachment in VB.NET
Dim file as String = "C:\attachment.dat"
If Not file = "" Then
Dim MsgAttach As New Attachment(file)
Email Attachment in C#
string file = @"C:\attachment.dat";
Attachment MsgAttach = new Attachment(file);
Basically thats all we need to learn to send email using .NET. I also created a VB.NET class that has all email sending functions.
Here's how you can call the ready-to-use class in your application:
Dim oEmail As New clsEmail
oEmail.SendEmailMessage(From_Email, From_Name, strEmailTo, "Event Notification", BodyMsg, "")
You can download the class from Mediafire
For more .NET tips and tricks, subscribe now