It is easy to send email in .net through Gmail using the System.Net.Mail namespace. The below example will help you to send a simple plain mail using Gmail SMTP method. MailMessage Class has a lot of properties which can be used if you need to build a mail application.
C# Code to send email in .net through Gmail
using System.Net; using System.Net.Mail; var fromAddress = new MailAddress("from@gmail.com", "From Name"); var toAddress = new MailAddress("to@example.com", "To Name"); const string fromPassword = "fromPassword"; const string subject = "Subject"; const string body = "Body"; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { smtp.Send(message); }
Let us take another example to send email in .net through Gmail using file attachment.
using System.Net; using System.Net.Mail; public void email_send() { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); mail.From = new MailAddress("from@gmail.com"); mail.To.Add("to@gmail.com"); mail.Subject = "Your Subject"; mail.Body = "Body Content goes here"; System.Net.Mail.Attachment attachment; attachment = new System.Net.Mail.Attachment("c:/file.txt"); mail.Attachments.Add(attachment); SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential("from@gmail.com", "mailpassword"); SmtpServer.EnableSsl = true; SmtpServer.Send(mail); }
Few of the MailMessage Properties which you should be knowing while using the above method.
- Mail Attachments: If you would like to send any attachments in the mail then you could use System.Net.Mail.Attachment attachment =new System.Net.Mail.Attachment(“c:/file.txt”); and then add the attachment to your MailMessage object using mail.Attachments.Add(attachment);
- HTML Body: If you would like to send the HTML content message in the mail then you should set the MailMessage HTML property as mail.IsBodyHtml = true;
- CC and BCC Address: If you would like to add the CC and BCC mail address then you should use the below properties to achieve this functionality.
mail.CC.Add("ccaddress@gmail.com"); mail.Bcc.Add("bccaddress@gmail.com");
- Delivery Notifications: If you would like to get the delivery notification on success or failure then you can set the delivery notification type while sending the message.
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;