Post

Sending Email using your GMail Account in C#.NET

Use System.Net.Mail namespace, not the deprecated System.Web.Mail. Doing SSL with System.Web.Mail will get security problems

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System.Net.Mail;

var client = new SmtpClient;
{
    //create a host
    Host = "smtp.gmail.com",
    //gmail uses port number 587
    Port = 587,
    //Enable Secure Communication
    EnableSsl = true,
    //Set delivery method to Network
    DeliveryMethod = SmtpDeliveryMethod.Network,
    //Give the Credentials
    Credentials = new NetworkCredential("yourusername@gmail.com", "yourPassword"),
    //Set some timeout
    Timeout = 20000
};

//Create a MailMessage Object
using (var mailMessage = new MailMessage("yourusername@gmail.com", toEmailId)
{
    //add subject and EmailBody(content) to Mail Message object
    Subject = 'Subject of the Email',
    Body = 'Content of the Email'
})
{
    //Send the Message...
    client.Send(mailMessage);
}

This post is licensed under CC BY 4.0 by the author.