ASPNetFAQ.com: What is ASP.NET?

Technology posts on ASP.NET, IIS, Windows (+ a little Linux), Cloud Servers, Hosting, and more!
  • Blog Home
Search the site...

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

Tweet
Share2
2 Shares

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+

More from my site

  • SQL Server restore failure and resolutionSQL Server restore failure and resolution
  • Great Pointers For Analyzing Memory Crash DumpsGreat Pointers For Analyzing Memory Crash Dumps
  • Changes are not allowed while code is runningChanges are not allowed while code is running
  • Video: Create ASP.NET web app and SQL Server databaseVideo: Create ASP.NET web app and SQL Server database
  • Sending Authenticated Email from ASP.NET C#Sending Authenticated Email from ASP.NET C#
Tweet
Share2
2 Shares

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

  1. ramesh says:
    March 18, 2012 at 8:28 am

    thanks

  2. Mohammed asif says:
    June 24, 2012 at 10:32 pm


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

    SmtpClient SMTPServer = new SmtpClient(server);

  3. Brad Kingsley says:
    July 19, 2012 at 7:50 am

    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.

  4. ajay says:
    August 3, 2012 at 1:06 am

    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

  5. Daniel Magana says:
    October 22, 2012 at 11:22 am

    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

    • Brad Kingsley says:
      October 23, 2012 at 6:21 am

      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.

    • Debashree Dey says:
      March 25, 2013 at 4:52 am

      :eek: Wao it worked

  6. Hitesh says:
    November 8, 2012 at 3:32 am

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

  7. farzad says:
    November 20, 2012 at 3:32 am

    tanx code is working !!! :razz:

  8. Sravani says:
    December 6, 2012 at 11:07 pm

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

  9. Shyma says:
    December 17, 2012 at 1:55 pm

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

  10. Brad Kingsley says:
    February 27, 2013 at 8:49 am

    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/).

  11. Brad Kingsley says:
    February 28, 2013 at 9:25 am

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

  12. faisal says:
    March 8, 2013 at 10:46 am

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

    • Brad Kingsley says:
      March 8, 2013 at 10:48 am

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

  13. Murtaza says:
    March 19, 2013 at 11:14 pm

    hey… It doesn’t work for me…

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

    :sad:

  14. arpit says:
    March 23, 2013 at 2:40 am

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

    • Brad Kingsley says:
      March 27, 2013 at 6:32 am

      Maybe try SMTP4DEV?
      http://smtp4dev.codeplex.com/

  15. workaz says:
    April 3, 2013 at 5:34 am

    Thanks very much

  16. eric kanzz says:
    May 24, 2013 at 2:54 am

    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 ?

  17. Brad Kingsley says:
    July 15, 2013 at 6:03 am

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

  18. Brad Kingsley says:
    July 19, 2013 at 3:22 pm

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

  19. sima says:
    July 21, 2013 at 5:07 am

    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

  20. shawn says:
    August 24, 2013 at 9:20 am

    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!

Proverbs 19:20

"Get all the advice and instruction you can, so you will be wise the rest of your life."

A Note On WordPress Hosting

Our main focus is of course .NET, but with a mix of Linux, virtualization, and other technologies. But if you're really looking for the best WordPress hosting specifically, read my WordPress host review to save yourself hassle AND money!




Recent Posts

  • What makes good web hosting?
  • jQuery Mobile C# ASP.NET and N5 Networks Software Repository
  • Open Source Bug Tracking Software and the Orchard Project
  • ASP.NET Development with Dreamweaver MX: Visual QuickPro Guide
  • Kendo UI Sample, ASP.NET Ajax Tutorial & More

Tags

ASP.NET Automation centos CMS css cytanium Development/Coding Email gmail Hosting htaccess http https IIS javascript Learning Linux logparser MySQL nginx openssl OrcsWeb performance PowerShell redirect RHEL security server SherWeb smtp SQL/Databases ssl System Administration telnet terminal tip Troubleshooting Ubuntu virtualization Visual Studio web farm web hosting Windows windows server Wordpress

Categories

  • ASP.net development
  • Development/Coding
  • Hosting
  • IIS (Internet Information Services)
  • SQL/Databases
  • System Administration
  • Virtualization
(c) ASPNETFAQ.com