How to send email alert

Hi Everyone,

I am trying to set up an email alert feature. A pretty basic one. What I am trying to do is for the system to send an email alert when a command button is clicked. I am running my system on a local server.

Any ideas how I could do this. I have tried making changes to the web.config file but no luck. I have attached my aspx.cs and web.config file to this question.

please Help!
Web.Config

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


ASPX.CS file


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;

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

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

    protected void btnSend_Click(object sender, EventArgs e)
    {

//create the mail message
MailMessage mail = new MailMessage();

//set the addresses
mail.From = new MailAddress("friendlysite@fs.com", "Friendly Site");
mail.To.Add("aa@aa.ac.uk");

//set the content
mail.Subject = "Arrangement of Lift";
mail.Body = "New message received. Please check your 'inbox'.";

//send the message
SmtpClient smtp = new SmtpClient("127.0.0.1");
smtp.Send(mail);
}

    }

Open in new window

xmalcolmAsked:
Who is Participating?
 
Alfred A.Connect With a Mentor Commented:
Try this function,


   1. public bool SendEmail(string StrMailfrom, string StrMailTo, string StrMailSubj, string StrMailBody)
   2. {
   3.    
   4.     System.Net.Mail.MailMessage Msg = new System.Net.Mail.MailMessage();
   5.     MailAddress FromAddress = new MailAddress(StrMailfrom);
   6.     MailAddress ToAddress = new MailAddress(StrMailTo);
   7.    
   8.     SmtpClient SMTPSrv = new SmtpClient("127.0.0.1");
   9.    
  10.     Msg.From = FromAddress;
  11.     Msg.To.Add(StrMailTo);
  12.     Msg.Subject = StrMailSubj;
  13.     Msg.Priority = System.Net.Mail.MailPriority.High;
  14.     Msg.Body = StrMailBody;
  15.     Msg.IsBodyHtml = true;
  16.    
  17.     try {
  18.            
  19.         SMTPSrv.Send(Msg);
  20.     }
  21.     catch (Exception ex) {
  22.         //'SendMail Error Occured
  23.        
  24.         return false;
  25.     }
  26.     finally {
  27.         Msg.Dispose();
  28.         SMTPSrv = null;
  29.     }
  30.    
  31.     return true;
  32. }

Open in new window

0
 
Alfred A.Connect With a Mentor Commented:
Also,

For accessing

<appSettings>
    <add key="smtpServer" value="127.0.0.1" />
  </appSettings>

You can do this in your code

SmtpClient smtp = new SmtpClient(ConfigurationManager.AppSettings("smptServer"));


Just be sure you have ->  using System.Configuration;  namespace and have a corresponding reference to System.Configuration in your project.

0
 
xmalcolmAuthor Commented:
Hi Alfred,

Thanks for your reply, but how do I initiate the method if I am putting the code in a different class. The way I have done it is attached to this response. Where am I going wrong? Sorry I am very new to this so still learning.
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;

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

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

    protected void btnSend_Click(object sender, EventArgs e)
    {
        
    }
    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("UoBCarShareScheme@uobcss.com", "UoB Car Share Scheme");
        MailAddress ToAddress = new MailAddress("xg@brighton.ac.uk");
       
        SmtpClient SMTPSrv = new SmtpClient("127.0.0.1");
       
       Msg.From = FromAddress;
       Msg.To.Add("xg@brighton.ac.uk");
       Msg.Subject = "Arrangement of Lift";
      Msg.Priority = System.Net.Mail.MailPriority.High;
      Msg.Body = "New message received. Please check your 'inbox'.";
      Msg.IsBodyHtml = true;
    
     try {
            
         SMTPSrv.Send(Msg);
      }
      catch (Exception) {
         //'SendMail Error Occured
         
           return false;
       }
       finally {
           Msg.Dispose();
          SMTPSrv = null;
      }
      return true;
        }

    }

Open in new window

0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
xmalcolmAuthor Commented:
Hi Alfred,

I also get this error message ("No connection could be made because the target machine actively refused it 127.0.0.1:25")

When I try doing this:

protected void btnSend_Click(object sender, EventArgs e)
    {
        System.Net.Mail.MailMessage Msg = new System.Net.Mail.MailMessage();
        MailAddress FromAddress = new MailAddress("UoBCarShareScheme@uobcss.com", "UoB Car Share Scheme");
        MailAddress ToAddress = new MailAddress("xaviermalcolm@btinternet.com");

        SmtpClient SMTPSrv = new SmtpClient("127.0.0.1");

        Msg.From = FromAddress;
        Msg.To.Add("xaviermalcolm@btinternet.com");
        Msg.Subject = "Arrangement of Lift";
        Msg.Priority = System.Net.Mail.MailPriority.High;
        Msg.Body = "New message received. Please check your 'inbox'.";
        Msg.IsBodyHtml = true;
        SMTPSrv.Send(Msg);
    }
0
 
Alfred A.Connect With a Mentor Commented:
1.  You can create a class library and put the method in there

For example,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1
{
    public class SendClass
    {
          public bool SendEmail(string StrMailfrom, string StrMailTo, string StrMailSubj, string StrMailBody)
         {
              //Send Email Code here
         }

    }
}


2.   Access the class by instantiating it in your page, something like the code below,

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;

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(value1,value2,value3,value4);   //note values are for example only!  you need to put your own values.
    }
}


note:

InstanceSend.SendEMail("UoBCarShareScheme@uobcss.com","xg@brighton.ac.uk","Arrangement of Lift","New message received. Please check your 'inbox'.");

Or,

pass it using variables.
0
 
xmalcolmAuthor Commented:
Hi Alfred,

I created a class library file and called it SendClass.cs in App_Data Folder.

Put the following code:

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.Collections.Generic;

namespace EmailAlert
{
    public class SendClass
    {
        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("UoBCarShareScheme@uobcss.com", "UoB Car Share Scheme");
            MailAddress ToAddress = new MailAddress("xg@brighton.ac.uk");

            SmtpClient SMTPSrv = new SmtpClient("127.0.0.1");

            Msg.From = FromAddress;
            Msg.To.Add("xg@brighton.ac.uk");
            Msg.Subject = "Arrangement of Lift";
            Msg.Priority = System.Net.Mail.MailPriority.High;
            Msg.Body = "New message received. Please check your 'inbox'.";
            Msg.IsBodyHtml = true;

            try
            {
                SMTPSrv.Send(Msg);
            }

            catch (Exception)
            {
                //'SendMail Error Occured

                return false;
            }

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

            }
            return true;
        }
    }
      }


and on my aspx.cs page done this:

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;

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("sdad@uobcss.com", "xg@brighton.ac.uk", "Arrangement  of Lift", "New message received. Please check your 'inbox'.");
        }
    }

But it doesnt pick up on SendClass - I get a red underline saying 'Send Class could not be found'


0
 
Alfred A.Connect With a Mentor Commented:
It is a namespace reference issue, put this in your "using" group

using EmailAlert;
0
 
xmalcolmAuthor Commented:
Hi Alfred,

That seems to have sorted out the issue and it compiles fine too.
But, I have not received an email. Why am I not getting any message?

I have attached my code so far.
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
    {
        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("UoBCarShareScheme@uobcss.com", "UoB Car Share Scheme");
            MailAddress ToAddress = new MailAddress("xaviermalcolm@btinternet.com");

            SmtpClient SMTPSrv = new SmtpClient("127.0.0.1");

            Msg.From = FromAddress;
            Msg.To.Add("xaviermalcolm@btinternet.com");
            Msg.Subject = "Arrangement of Lift";
            Msg.Priority = System.Net.Mail.MailPriority.High;
            Msg.Body = "New message received. Please check your 'inbox'.";
            Msg.IsBodyHtml = true;

            try
            {
                SMTPSrv.Send(Msg);
            }

            catch (Exception)
            {
                //'SendMail Error Occured

                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("UoBCarShareScheme@uobcss.com", "xaviermalcolm@btinternet.com", "Arrangement  of Lift", "New message received. Please check your 'inbox'.");
        }
    }

Open in new window

0
 
xmalcolmAuthor Commented:
Also the bit that I am stating here isnt actually real. There isnt a domain name called uobcss.com
Could this be the reason why.

MailAddress FromAddress = new MailAddress("UoBCarShareScheme@uobcss.com", "UoB Car Share Scheme");
0
 
Alfred A.Commented:
OK.  Your original error I guess is still causing a problem.  However, this is being handled in your try-catch.  What I provided you in there is a skeletal construct.  You need to populate the catch part.

by the way, adjust your catch(Exception) to catch(Exception ex)

and then display the ex values (ex.Message, ex.Source, and ex.StackTrace) to determine what really went wrong.

I am still assuming the "No connection could be made because the target machine actively refused it 127.0.0.1:25"


And, Yes, if uobcss.com is not a real domain name and there is no SMTP authentication involved, it will rely on the From part.
0
 
xmalcolmAuthor Commented:
Hi Alfred,

What do you mean by populating the catch part?
Do you mean like this?

try
            {
                SMTPSrv.Send(Msg);
            }

            catch (Exception ex)
            {
                ex.Message;
                ex.Source;
                ex.StackTrace;
                return false;
            }

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

            }
            return true;

But an error I am getting is 'only assignment, call, increment ... can be used as a statement.

And for the 'From' field - can I use my email address or anything else?
0
 
Alfred A.Commented:
1.  Example (assuming you have variable _ErrorDescription as string)

catch (Exception ex)
{
      _ErrorDescription = ex.Message + " - " + ex.Source + " - " + ex.StackTrace
     return false;
}

You can do whatever you want from the values.  It is up to you on how you deal with it.


2.  Have you configured your SMTP Server?  Check the following out, I just don't know which IIS you are using but this will give you some idea:

http://www.cmsconnect.com/praetor/webhelpg2/Chapter_2_-_Pre-installation_considerations/Configuring_the_SMTP_Server.htm

http://www.ehow.com/how_5154281_configure-iis-smtp-server.html
0
 
xmalcolmAuthor Commented:
No I dont actually have variable _ErrorDescription as string declared. Where do I declare it?
0
 
Alfred A.Commented:
Hi,

_ErrorDescription is just an example. :-)

Well, I guess you can declare it at the start of the function as "string _ErrorDescription" for example, and do whatever you want with it.

Or you could just return the thrown error values as string if you want rather than returning a bool.  It is up to you.
0
 
xmalcolmAuthor Commented:
Hi Alfred.

thank you for the links I will look into them. I have declared "string ErrorDescription" as seen in the attached code which has sorted out the red underline and it compiles and I dont get any error messages.

I am sure I need to display it as message somewhere in a label named (lblError) in the aspx page. I tried putting that but it didnt work, probably because I am not putting it in the right place in the aspx.cs file.
Msg.From = FromAddress;
            Msg.To.Add("xg@brighton.ac.uk");
            Msg.Subject = "Arrangement of Lift";
            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 + "-" + ex.Source + "-" + ex.StackTrace;
                return false;
            }

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

            }
            return true;
        }

Open in new window

0
 
xmalcolmAuthor Commented:
Hi Alfred,

I found a solution. After much research, I decided to use gmail's smtp server for relaying which allowed me to send email alerts. I have attached the solution to this response. Thanks for all your help anyway.


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
 
xmalcolmAuthor Commented:
My completed solution has been attached. And thanks to Alfred for his help.
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.