In this tip, you will learn how to send an email in your ASP.NET application. This tip uses the Gmail account to send an email so you can send email on the fly. Here, you will get the sample code to send an email in ASP.NET application.
When I started my career in ASP.NET, I was totally clueless how to send an email in ASP.NET application. I Googled it and found too many answers and some of them didn't even work for me at all. After trying a couple of solutions, finally I was able to send my first email through an ASP.NET web application.
The ASP.NET namespace System.Net.Mail is handy when it comes to sending an email in ASP.NET application. So the first thing is to include this namespace in your code behind file. We will use the appropriate classes of this namespace for sending mail.
System.Net.Mail
47.Imports System.Net.Mail
We will use the following classes in our sample code:
MailMessage
SmtpClient
Attachment
Now I will come to the real thing. How to write code for sending a sample mail in an ASP.NET application. Here is the step by step procedure to send an email in ASP.NET.
Step 1: Open Visual Studio from your desktop.
Step 2: Create a new website and name it as "SendMail".
SendMail
Step 3: Create a new page and name it SendMail.aspx.
Step 4: Add a text box on the page and also add a button and label it as "Send Mail".
Step 5: In code behind of this page (on button's click event), copy paste the following code:
47.Protected Sub SendMail_Click(sender As Object, e As System.EventArgs) Handles btnSendMail.Click
48. Dim message As MailMessage = New MailMessage()
49. message.To.Add(New MailAddress("test@test.com"))
50. message.Subject = "This is a test message"
51. message.Body = "This is a test mail"
52. Dim mclient As SmtpClient = New SmtpClient()
53. mclient.Host = "smtp.gmail.com"
54. mclient.Port = 587
55. mclient.EnableSsl = True
56. message.Attachments.Add(New Attachment(Server.MapPath("~/FileName.doc")))
57. message.CC.Add("mail1@mailaddress.com")
58. message.Bcc.Add("mail1@mailaddress.com")
59. mclient.Credentials = New System.Net.NetworkCredential("Gmail user id", "Gmail password")
60. mclient.Send(message)
61.End Sub
63.message.IsBodyHtml = "True"
64.message.Body = "<p>" + "This is a test mail" + "</p>"
mClient
SmtpClient
Host
Port
EnableSSL
58.message.Attachments.Add(New Attachment(Server.MapPath("~/FileName.doc")))
59.message.CC.Add("mail1@mailaddress.com")
60.message.Bcc.Add("mail1@mailaddress.com")
61.mclient.Credentials = New System.Net.NetworkCredential("Gmail user id", "Gmail password")
This is perhaps the easiest and simplest method for newbies to send an email in ASP.NET application. You can also use your personal GMail account to send email in an ASP.NET application.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)