Monday, August 3, 2009

SENDING A MAIL FROM ASP.NET APPLICATION

IN DEFAULT.ASPX PLACE A BUTTON AND IN THE BUTTON CLICK EVENT WRITE THE FOLLOWING CODE

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
//Calling the function SendMail
Response.Write(SendMail("vaidadi.bobby@gmail.com", "meetudmeet@gmail.com", "meetudmeet@yahoo.com", "Test Mail", "Test Mail Body"));
}
public string SendMail(string toList, string from, string ccList, string subject, string body)
{
MailMessage message = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
string msg = string.Empty;
try
{
MailAddress fromAddress = new MailAddress(from);
message.From = fromAddress;
message.To.Add(toList);
if (ccList != null && ccList != string.Empty)
message.CC.Add(ccList);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential("MY@gmail.com", "MYPASSWORD");
smtpClient.EnableSsl = true;
smtpClient.Send(message);
msg = "Successful";
}
catch (Exception ex)
{
msg = ex.Message;
}
return msg;
}
}

No comments: