Click here to Skip to main content
15,915,019 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi ,
I am using the below code for sending email using gmail SMTP server. But i am not able to send an email.Please review my code and help me as early as possible.

C#
MailMessage mail = new MailMessage();
mail.From = new MailAddress("from gmail emailid");
mail.To.Add("to gmail emailid");
mail.IsBodyHtml = true;
mail.Subject = "Email Sent";
mail.Body = "Mail Done";

SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = new System.Net.NetworkCredential(my gmail id", "my gmail password");
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Send(mail);
Posted
Updated 5-Aug-14 2:30am
v2
Comments
Thanks7872 5-Aug-14 8:30am    
"i am not able to send an email" is not informative at all.
knackCoder 5-Aug-14 8:37am    
Provide me with code for sending an email using Gmail SMTP server in ASP.NET.
[no name] 5-Aug-14 9:00am    
Okay, here you go
MailMessage mail = new MailMessage();
mail.From = new MailAddress("from gmail emailid");
mail.To.Add("to gmail emailid");
mail.IsBodyHtml = true;
mail.Subject = "Email Sent";
mail.Body = "Mail Done";

SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = new System.Net.NetworkCredential(my gmail id", "my gmail password");
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Send(mail);
Rudely demading code is not going to go over real well on the internet.
Ziee-M 5-Aug-14 9:05am    
mail.to.Add("x@x.com") you have to precise the reciver : if you executed that code it want work since the email is not valid.
smtp.Credential ("your email","your password"): you have to put in here the email that will send the message + the password.

1 solution

Be sure to use System.Net.Mail, not the deprecated System.Web.Mail. Doing SSL with System.Web.Mail is a gross mess of hacky extensions.

C#
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);
}
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900