Sending emails using your gmail account is very simple in C#/VB.NET using .NET framework 2.0+. The below code snippet shows how.
using System.Net;
using System.Net.Mail;
...
public static void SendMail(MailMessage msg)
{
SmtpClient smtp=new SmtpClient();
smtp.Host=”smtp.gmail.com”;
smtp.DeliveryMethod= SmtpDeliveryMethod.Network;
smtp.Credentials=new NetworkCredential(”[username”,”password”);
smtp.EnableSsl=true;
smtp.Send(msg);
}
We are creating a SmtpClient object and setting it’s various properties for sending mails. Replace the username/password with your gmail username/password and you should be ready to go.
You can call this method and pass it a MailMessage object like this.
MailMessage msg=new MailMessage(“from”,”to”,”subject”,”body”);
SendMail(msg);
Using config file instead of hard coding the mail settings
We can use the web.config (or app.config) file depending whether we are developing an C# ASP.NET or C# Desktop application for storing our mail settings like smtp host etc. This allows us to change the settings without recompiling the program. Paste the following code in your application’s config file between <configuration> and </configuration> tags.
<system.net>
<mailSettings>
<smtp from=”the from email” deliveryMethod=”Network”>
<network host=”smtp.gmail.com” userName=”username” password=”password” port=”587”/>
</smtp>
</mailSettings>
</system.net>
Now our SendMail() method will look like
public static void SendMail(MailMessage msg)
{
SmtpClient smtp=new SmtpClient();
smtp.EnableSsl=true;
smtp.Send(msg);
}
Now we don’t have username/password hard coded in our source code and code becomes more maintainable.