Skip to content

Sending Email in ASP .NET

Robert Greiner
Robert Greiner
1 min read

I can't think of too many websites that don't send automated email. Unfortunately, for ASP .NET programmers, there are several incorrect and out-of-date code snippets online which try to explain how to send email.

Here's the code I use on the contact form for my personal website which does the trick quite nicely.

/* using System.Net.Mail; */
MailMessage newMail = new MailMessage();
newMail.To.Add(toAddress);
newMail.Subject = subject;
newMail.Body = body;
newMail.From = new MailAddress(fromAddress, name);
newMail.IsBodyHtml = true;

SmtpClient SmtpSender = new SmtpClient();
SmtpSender.Port = 25; //or, whatever port your SMTP server operates on
SmtpSender.Host = "mail.yourdomain.com";
SmtpSender.Send(newMail);

Here, I'm using MailMessage to build the actual email message to be sent and SmtpClient to do the actual sending.

Now, the Web.config file needs to be updated so the server knows your email account credentials.

Add this code to your Web.config file before the final </configuration> tag:

<system.net>
  <mailSettings>
    <smtp>
      <network defaultCredentials="false" 
           host="mail.yourdomain.com" port="25" 
           userName="name-to-send-email@yourdomain.com" 
           password="*****"/>
     </smtp>
   </mailSettings>
</system.net>

Now, you should be able to send automated email messages to your heart's content. Enjoy.

Image From blueskyfactory

Please consider subscribing, it's free.
Technology

Robert Greiner Twitter

Professional optimist. I write a weekly newsletter for humans at the intersection of business, technology, leadership, and career growth.


Related Posts

Members Public

AI Rule #1 - Customer First

In 1985, Warren Buffett wisely said, "The first rule of investment is don't lose. And the second rule of investment is don't forget the first rule, and that's all the rules there are." Similarly, the first rule of AI investment is to

AI Rule #1 - Customer First
Members Public

Navigating the Upside Down as a Technology Leader

Ideas for leading technology organizations with confidence and creativity.

Navigating the Upside Down as a Technology Leader
Members Public

Artist for a Day

The future of creative output is multiplied by AI.

Artist for a Day