Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / system

Using Gmail Account to Send Emails With Attachment

4.76/5 (70 votes)
26 Sep 2013CPOL 163.2K   1  
Sending Email using Gmail account from your application.

The following piece of code will let you send email using the Google server. Just replace the network credentials with your Google user name and password.

C#
//Short Method
try
{
    SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = new NetworkCredential("username", "password");
    smtp.EnableSsl = true;
    smtp.Send("sender@gamil.com", "receiver", "subject", "Email Body");
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
}
C#
//Detailed Method
try
{
    MailAddress mailfrom = new MailAddress("sender@gmail.com");
    MailAddress mailto = new MailAddress("receiver@abc.com");
    MailMessage newmsg = new MailMessage(mailfrom, mailto);

    newmsg.Subject = "Subject of Email";
    newmsg.Body = "Body(message) of email";

    //For File Attachment, more file can also be attached
    Attachment att = new Attachment("C:\\...file path");
    newmsg.Attachments.Add(att);

    SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = new NetworkCredential("username","password");
    smtp.EnableSsl = true;
    smtp.Send(newmsg);    
} 
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
}

Note: Before providing the credentials, you need to set UserDefaultCredentials to false. The above mentioned settings are for Gmail, but you can also use other SMTP servers like Yahoo!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)