Sometimes we need to send emails from our Web application without any SMTP setup. For example, sending message with important website updates.
We can send emails from a server IP address without specifying an mail credentials. This is done via IIS and hosting a web page on IIS. The server IIS must support SMTP and emails.
Setup IIS for Emails
- Launch IIS
- Select default SMTP Virtual Server, right click on it and select Properties.
- General tab > Advanced : Add your local IP address
- Hit OK
Use SmtpClient to send Emails
Now, your IIS is all set to send emails from your local IP address.
Create an ASP.NET Website or use your existing website and write the below code.
On our case, we have a simple ASP.NET web page and a button. On the button click event hander, this code sents an email. You can download the attached code.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Net.Mail;
- using System.Net;
- public partial class _Default : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- SmtpClient ss = new SmtpClient("<Your Local IP Addres>");
- ss.Port = 25;
- ss.UseDefaultCredentials = true;
- ss.Send("<From Mail>", "<To Mail>", "<Subject>", "<Body message>");
- }
- }
- }
In the above code, SmtpClient object uses your local IP address. Next, set a Port and use default credentials. The last thing is to send email via Send method. The format of the email can be anything you want to put in the Send method.
Here are couple of more articles on how to send emails in C#.