All posts tagged iis mail

how to send mail in asp.net

Today i will show you how to mail in asp.net.

This is realy a easy task. Microsoft has  built-in section for SmtpClient settings.

<configuration>
  <system.net>
    <mailSettings>
      <smtp deliveryMethod="network">
        <network
          host="localhost"
          port="25"
          defaultCredentials="true"
        />
      </smtp>
    </mailSettings>
  </system.net>
</configuration>

So when you click the button it take all the information and send to Mailer class. Then it mail.
If you want to use google smtp then you have to uncomment sc.EnableSsl = true; in Mailer class.
Default smtp port for localhost is 25 and for google 587.
If you do not need user name and password then keep that blank.
http://msdn.microsoft.com/en-us/library/w355a94k.aspx

using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Configuration;
using System.Collections.Generic;

public class Mailer
{
 /// <summary>
    /// Send Email without attachment
    /// </summary>
    /// <param name="messagefrom">Email from address</param>
    /// <param name="toaddress">Email to address</param>
    /// <param name="subject">Email subject</param>
    /// <param name="body">Email body</param>
    /// <param name="ishtml">True if the body contains HTML</param>
    /// <returns></returns>

public static bool Send(string messagefrom, string toaddress, string subject, string body, bool ishtml)
{
MailMessage message;

SmtpClient sc = new SmtpClient();

// sc.EnableSsl = true;  //   for some domain which need ssl //
try
{

message = new MailMessage();
message.To.Add(toaddress);
message.From = new MailAddress(messagefrom);

message.Subject = subject;
message.Body = body;

message.IsBodyHtml = ishtml;

sc.Send(message);

return true;
}
catch (Exception ex)
{
throw ex;
}
}

}

Now we make mail form which you can see

Demo

Bellow is the asp.net code for this form.

protected void btn_feedback_Click(object sender, EventArgs e)
{
string from = txtFromemail.Text; ;

string subject = txtsubject.Text;
string to = "reciver email address";

string body = txtmsg.Text;

Mailer.Send(from, to, subject, body, true);

Response.Redirect("response address");
}

So when you click the button it take all the information and send to Mailer class. Then it mail.
If you want to use google smtp then you have to uncomment  sc.EnableSsl = true; in Mailer class.

Default smtp port for localhost is 25 and for google 587.
If you do not need user name and password then keep that blank.
For more information on mailSettings see http://msdn.microsoft.com/en-us/library/w355a94k.aspx