Tuesday, February 21, 2012

How to send email in asp.net


 

To send mail you can use ‘System.Net.Mail’.

Code-Behind:

  Using System.Net.Mail;
public void SendEmail(string from, string to, string bcc, string cc, string subject,
string body)
{
    try
    {  
        MailMessage NewEmail = new MailMessage();
        NewEmail.From = new MailAddress(from);
        NewEmail.To.Add(new MailAddress(to));
        if (!String.IsNullOrEmpty(bcc))
        {
            NewEmail.Bcc.Add(new MailAddress(bcc));
        }
        if (!String.IsNullOrEmpty(cc))
        {
            NewEmail.CC.Add(new MailAddress(cc));
        }
        NewEmail.Subject = subject;
        NewEmail.Body = body;
        NewEmail.IsBodyHtml = true;
        SmtpClient mSmtpClient = new SmtpClient();
        // Send the mail message
        mSmtpClient.Send(NewEmail);
        this.Label1.Text = "Email sent successful.";
    }
    catch
    {
        this.Label1.Text = "Email sent failed";
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
    string from = "sender address";// like username@server.com
    string to = TextBox1.Text; //Recipient address.
    string bcc = "";
    string cc = "";
    string subject = "text";
    string body = "text";
    SendEmail(from, to, bcc, cc, subject, body); }
Web.Config:
<system.net>
  <mailSettings>
    <smtp>
      <network host="your stmp server" port="25" userName="your from email" password="your password"/>
    </smtp>
  </mailSettings>
</system.net>

 

Related thread:

http://forums.asp.net/t/1207868.aspx

1 comment: