Code to Send an Email in C#

dotnetlogo
Want to send an email from your .net application?
Just use the following code and don’t forget to put in the valid SMTP server id in the code and your email will be sent.

using System.Web.Mail;
private bool SendEmail(string sFrom, string sTo, string sCC,
string sBCC, string sSubject, string sMessage, int iMailType)
{
try
{
MailMessage Message = new MailMessage();

// If sFrom is blank, system mail id is assumed as the sender.
if(sFrom==””)
Message.From = “[email protected]”;
else
Message.From = sFrom;

// If sTo is blank, return false
if(sTo==””)
return false;
else
Message.To = sTo;

Message.Cc = sCC;
Message.Bcc = sBCC;
Message.Subject = sSubject;
Message.Body = sMessage;
Message.BodyFormat = MailFormat.Text;
SmtpMail.SmtpServer = “Put a valid smtp server IP”;
SmtpMail.Send(Message);

return true;
}
catch(System.Web.HttpException ehttp)
{
// Your exception handling code here…
return false;
}
catch(Exception e)
{
// Your exception handling code here…
return false;
}
catch
{
// Your exception handling code here…
return false;
}
}

Anky Goyal

I am MCPD certified in .NET and working on .NET technologies for past 3yrs. I am very passionate about the new features which get introduced in the technology. I am here to share the new features i get to know in the world of Microsoft. Follow me on twitter @ankygoyal [email protected]Ankit Goyal

More Posts - Website