How to send email alert using ASP.Net with C#

Hi Everyone,

I am trying to set up an automated feature so that when a command button is clicked, the system sends a small message as email, alerting a new message that has been received.

I do not have a domain name and I only need it work as a demonstration. How can I do this for free? I have attached my web.config file and aspx.cs code.

Also guys could you tell me how can I output the error message from method 'ex' to a label? It compiles as I have now but it gives me an error. I am pretty new to all this so your help will be greatly appreciated.

web.config file


<configuration>
	<configSections>
		<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
			<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
				<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
				<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
					<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
					<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
					<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
					<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
				</sectionGroup>
			</sectionGroup>
		</sectionGroup>
	</configSections>
  <appSettings>
    <add key="smtpServer" value="127.0.0.1" />
  </appSettings>
	<connectionStrings>


aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.ComponentModel;
using System.Drawing;
using System.Web.SessionState;
using System.Net.Mail;
using EmailAlert;

namespace EmailAlert
{
    public class SendClass
    {
        Label lblError;

        public bool SendEmail(string StrMailfrom, string StrMailTo, string StrMailSubj, string StrMailBody)
        {
            System.Net.Mail.MailMessage Msg = new System.Net.Mail.MailMessage();
            MailAddress FromAddress = new MailAddress("aa@localhost.com");
            MailAddress ToAddress = new MailAddress("aa@aa.com");

            SmtpClient SMTPSrv = new SmtpClient("127.0.0.1");

            Msg.From = FromAddress;
            Msg.To.Add("aa@aa.com");
            Msg.Subject = "hello";
            Msg.Priority = System.Net.Mail.MailPriority.High;
            Msg.Body = "New message received. Please check your 'inbox'.";
            Msg.IsBodyHtml = true;
            String ErrorMessage;
            try
            {
                SMTPSrv.Send(Msg);
            }

            catch (Exception ex)
            {
                ErrorMessage = ex.Message.ToString() + "-" + ex.Source.ToString() + "-" + ex.StackTrace.ToString();
                lblError.Text = ex.ToString();
                return false;
            }

            finally
            {
                Msg.Dispose();
                SMTPSrv = null;

            }
            return true;
        }
    }
}

public partial class MessagingPage : System.Web.UI.Page
    {

        private void Page_Load(object sender, EventArgs e)
        {
           
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            SendClass InstanceSend = new SendClass();
            bool IsSent = InstanceSend.SendEmail("ss@localhost.com", "aa@aa.com", "hello", "New message received. Please check your 'inbox'.");
        }
    }

Open in new window

xmalcolmAsked:
Who is Participating?
 
guru_samiConnect With a Mentor Commented:
Did  you get any error while trying Gmail?

How about adding this to your web.config:

<system.net>
<mailSettings>
       <smtp deliveryMethod="Network" from="test@test.com">
                <network host="smtp.gmail.com" port="587" userName="yourusername@gmail.com" password="yourgmailpassword" defaultCredentials="false"/>
            </smtp>
</mailSettings>
</system.net>

And this code to send email....
Note: For your label question you need to add a label on your page (not in code-behind)....and since you are using external library you need to return string from your sendEmail method instead of bool as shown in code below.

Unfortunately I did not get chance to play with google maps....



//you can adjust this method to take parameters...
public string SendEmail()
{ 
string message ="Failed";       
 SmtpClient client = new SmtpClient();
        MailMessage msg = new MailMessage();
        msg.From = new MailAddress("yourusername@gmail.com");
        msg.To.Add(new MailAddress("abcd@test.com"));
        msg.Subject = "This is a test Email subject";
        msg.Body = TextBox1.Text;
        try
        {
            client.Send(msg);
            message="Mail sent Successfully";
        }
        catch (Exception ex)
        {
            message=ex.Message;
        }
return message;
}


On aspx.cs

protected void btnSend_Click(object sender, EventArgs e)
        {
            SendClass InstanceSend = new SendClass();
            lblMessage.Text = InstanceSend.SendEmail("username@gmail.com", "to@email.com", "Arrangement  of Lift", "New message received. Please check your 'inbox'.");
        }

.aspx:

 <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>

Open in new window

0
 
guru_samiCommented:
Is this just for test purpose?
You can use gmail smtp to send email as shown here:
http://dotnetguts.blogspot.com/2006/10/send-email-from-gmail-in-aspnet-20.html

Or you can set this in your web.config:
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory" from="test@abc.com" >
  <specifiedPickupDirectory pickupDirectoryLocation="C:\TestPickup"/>
</smtp>
</mailSettings>
</system.net>

Using the above ....the email will be in the C:\TestPickup where you can inspect it....
0
 
xmalcolmAuthor Commented:
Hi Guru Sami,

thank you for looking into my problem. I must say I feel quite honoured to have received your attention.

Thank you for the suggestion, I just read it but I have already did what you suggested just recently. I have attached my completed solution to this response.

Guru sami, you dont by any chance know much about google maps do you? if so I would be grateful if you could help me out a bit.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.ComponentModel;
using System.Drawing;
using System.Web.SessionState;
using System.Net.Mail;
using System.Net;
using EmailAlert;

namespace EmailAlert
{
    public class SendClass
    {
        public bool SendEmail(string StrMailfrom, string StrMailTo, string StrMailSubj, string StrMailBody)
        {
            MailMessage Msg = new MailMessage();
            MailAddress FromAddress = new MailAddress("username@gmail.com", "Friendly Name");
            MailAddress ToAddress = new MailAddress("to@email.com");

            Msg.From = FromAddress;
            Msg.To.Add(StrMailTo);
            Msg.Subject = StrMailSubj;
            Msg.Body = StrMailBody;
            Msg.Priority = MailPriority.High;
            Msg.IsBodyHtml = true;
            
            SmtpClient client = new SmtpClient();
            client.Credentials = new NetworkCredential("username@gmail.com", "*******");
            client.Port = 587;
            client.Host = "smtp.gmail.com";
            client.EnableSsl = true;
            object userState = Msg;
            try
            {
                client.Send(Msg);
            }

            catch (Exception)
            {
                
                return false;
            }

            finally
            {
                Msg.Dispose();
                client = null;

            }
            return true;
        }
    }
}

public partial class MessagingPage : System.Web.UI.Page
    {

        private void Page_Load(object sender, EventArgs e)
        {
           
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            SendClass InstanceSend = new SendClass();
            bool IsSent = InstanceSend.SendEmail("username@gmail.com", "to@email.com", "Arrangement  of Lift", "New message received. Please check your 'inbox'.");
        }
    }

Open in new window

0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
guru_samiCommented:
I think you already had your code working right....? Did I read it wrong...that you had problem getting it work?
0
 
xmalcolmAuthor Commented:
Hi guru,

No I dont get any errors as it is. But I made some of the changes you suggested above. One more thing guru - do you know how I could feed rss data to my website. I want to use a feed from another website to show on mine.

This links looks interesting but I dont know how to do the xml bit as mine is in C#.
http://www.codeproject.com/KB/XML/RSSFeedEx.aspx
0
 
xmalcolmAuthor Commented:
Yeh my code was working previously :))
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.