Last night I was thinking to write a small post about sending emails using .NET. Then I thought of using GMAIL smtp account to send email. So here is the code.
using System;
using System.Net;
using System.Net.Mail;
/// <summary>
/// Email Sending Class for GMAIL account.
/// </summary>
public class Emails
{
public Emails()
{
//
// TODO: Add constructor logic here
//
}
public string sendmail(string body)
{
try
{
MailMessage mail=new MailMessage();
mail.To.Add(new MailAddress("xxxx@gmail.com"));
mail.From= new MailAddress("yyyy@gmail.com");
mail.Body=body;
SmtpClient smtp=new SmtpClient("smtp.gmail.com",587);
smtp.Credentials=new NetworkCredential("yyyy@gmail.com", "#&&$$%#%"); // This is where you have to specify account properties of the email account you are using to send email. yyyy@gmail.com is the userid and #&&$$%#% is the password.
smtp.EnableSsl=true;
smtp.Send(mail);
return "Success";
}
catch(Exception ex)
{
return "Failed";
}
}
}
Now from here you can call this class and send email. I have used the static emails here but you can make it change accordingly to use it as dynamically. You will need to add more paramaters like "body" in calling this function.
Thanks.