Using Gmail to send email from C-Sharp

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.


    private
void button_send_Click(object sender, EventArgs e)
    {
       
//Short Method
        SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new NetworkCredential("username","password");
        smtp.EnableSsl = true;
        smtp.Send("[email protected]", "receiver", "subject", "Email Body");

 
       
//Detailed Method
        MailAddress mailfrom = new MailAddress("[email protected]");
        MailAddress mailto = new MailAddress("[email protected]");
        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);
    }


I have kept the code simple, using or try-catch blocks can be added as per need.

Have a nice time. Do give suggestions and comments.

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. DNJXJ-7XBW8-2378T-X22TX-BKG7J

Ebook Download
View all
Learn
View all