Below is sample code showing how to send email from ASP.Net 4 using C#. With this code I am assuming that the server already has a local SMTP service installed, so I use “localhost” to relay the email.

(Here is a Razor C# example)

[NOTE: I guess it isn’t obvious, but you need a working SMTP service for sending email – from code or otherwise in general. This code assumes you have an SMTP service working and configured for relay on the same machine that is running the code. If you don’t have SMTP installed and are on Windows 8 or earlier, try this product -> smtp4dev. If you are running Windows Server 2008, install the MS SMTP service, then configure it to allow local relay.]

[UPDATE: Someone rightly pointed out that this example, if used 100% as-is, would create an open-relay situation and would quickly be abused by spammers. You should most certainly handle the From address as a variable defined and controlled by your code; and you should do something similar with the TO addresses, likely pulling them from a data source is this is a large mailing, or coding that to a variable also if this is just a feedback or contact form.]

Here is the SendMail.aspx page:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SendMail.aspx.cs" Inherits="SendMail" %>
<html>
<head runat="server"><title>Email Test Page</title></head>
<body>
    <form id="form1" runat="server">
        Message to: <asp:TextBox ID="txtTo" runat="server" /><br>
        Message from: <asp:TextBox ID="txtFrom" runat="server" /><br>
        Subject: <asp:TextBox ID="txtSubject" runat="server" /><br>
        Message Body:<br>
        <asp:TextBox ID="txtBody" runat="server" Height="171px" TextMode="MultiLine" Width="270px" /><br>
        <asp:Button ID="Btn_SendMail" runat="server" onclick="Btn_SendMail_Click" Text="Send Email" /><br>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>
</body>
</html>

Here is the source code of the SendMail.aspx.cs page:

using System;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class SendMail : System.Web.UI.Page
{
    protected void Btn_SendMail_Click(object sender, EventArgs e)
    {
        MailMessage mailObj = new MailMessage(
            txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
        SmtpClient SMTPServer = new SmtpClient("localhost");
        try
        {
           SMTPServer.Send(mailObj);
        }
            catch (Exception ex)
        {
            Label1.Text = ex.ToString();
        }
    }
}

Happy hosting!
Brad on Google+

Be Sociable, Share!
    Sending email from ASP.Net 4 – C# sample code

    24 thoughts on “Sending email from ASP.Net 4 – C# sample code

    • March 18, 2012 at 8:28 am
      Permalink

      thanks

    • June 24, 2012 at 10:32 pm
      Permalink


      May be in the place of Localhost you need to type server

      SmtpClient SMTPServer = new SmtpClient(server);

    • July 19, 2012 at 7:50 am
      Permalink

      With this sample code the web.config doesn’t matter. Upload your own – or don’t use one at all if you don’t want to.

    • August 3, 2012 at 1:06 am
      Permalink

      i m getting this error.ur code is not working….

      System.Net.Mail.SmtpException: Failure sending mail. —> System.Net.WebException: Unable to connect to the remote server —> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:25 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) — End of inner exception stack trace — at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout) at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback) at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port) at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port) at System.Net.Mail.SmtpClient.GetConnection() at System.Net.Mail.SmtpClient.Send(MailMessage message) — End of inner exception stack trace — at System.Net.Mail.SmtpClient.Send(MailMessage message) at _Default.Btn_SendMail_Click(Object sender, EventArgs e) in e:\Ajay\sendmail\sendmail.aspx.cs:line 27

    • October 22, 2012 at 11:22 am
      Permalink

      It worked out for me, thanks!

      I just changed:

      SmtpClient SMTPServer = new SmtpClient(“10.113.136.188″);

      Instead of:

      SmtpClient SMTPServer = new SmtpClient(“localhost”);

      Regards

      • October 23, 2012 at 6:21 am
        Permalink

        Great! Yes, you can change the SMTPServer to a different value if you have a remote SMTP service running somewhere other than the local machine that you prefer to use.

      • March 25, 2013 at 4:52 am
        Permalink

        :eek: Wao it worked

    • November 8, 2012 at 3:32 am
      Permalink

      Error:-‘System.Net.Mail.MailMessage’ does not contain a constructor that takes ‘3’ arguments

    • November 20, 2012 at 3:32 am
      Permalink

      tanx code is working !!! :razz:

    • December 6, 2012 at 11:07 pm
      Permalink

      I have got no errors,but mail not recieved :sad: .why?

    • December 17, 2012 at 1:55 pm
      Permalink

      It worked for me. Thanks for the concise code. Really appreciate it.

    • February 28, 2013 at 9:25 am
      Permalink

      Read the first note in the post to make sure you have an installed and configured SMTP service running on the local machine.

    • March 8, 2013 at 10:46 am
      Permalink

      i stated smtp using smtp4dev. but the mail is not delivered neither in spam or inbox of my email id

      • March 8, 2013 at 10:48 am
        Permalink

        You’ll need to do some troubleshooting with smtp4dev – I use MS SMTP so aren’t familiar with that other one.

    • March 19, 2013 at 11:14 pm
      Permalink

      hey… It doesn’t work for me…

      i didn’t got any error and i also didn’t got the mail…

      :sad:

    • March 23, 2013 at 2:40 am
      Permalink

      i have same error i have windows8 in my laptop hhow to configure smtp in my win8

    • April 3, 2013 at 5:34 am
      Permalink

      Thanks very much

    • May 24, 2013 at 2:54 am
      Permalink

      hey, I got an error at first, solved it.
      Now am getting no error but no mail was sent to any email address I sent the message to. What could be the problem ?

    • July 15, 2013 at 6:03 am
      Permalink

      Do you mean pulling email addresses from a SQL database and sending the same message to each of them?

    • July 19, 2013 at 3:22 pm
      Permalink

      That’s not a code issue – it’s an SMTP security issue.

    • July 21, 2013 at 5:07 am
      Permalink

      it’s working finally
      ممنون
      first it doesn’t working when I exchange from’s email with “to” it worked. :razz:
      if it had a message after sending it was great

    • August 24, 2013 at 9:20 am
      Permalink

      Here is a question regarding the permission errors above. I can take the exact same smtp code…run it in one .net 4 app and get success. If I move the code to another .net 4 app I get the same permission issues mentioned above. Any thoughts on what I should be look for? All code is running from the same local box out to the same remote smtp. Thanks!

    Comments are closed.