Sending email from ASP.Net 4 – C# sample code

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!

    24 Comments.


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

      SmtpClient SMTPServer = new SmtpClient(server);

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

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

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

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

    6. tanx code is working !!! :razz:

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

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

    9. That should be whoever you want the email to be “from”. Be sure you have the SMTP service to allow relay though (http://bradkingsley.com/configuring-microsofts-smtp-service-to-allow-relay/).

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

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

    12. hey… It doesn’t work for me…

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

      :sad:

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

    14. Thanks very much

    15. 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 ?

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

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

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

    19. 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!