问题
I am trying to send mail using gmail in asp.net
My Code:
using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
{
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
if (fuAttachment.HasFile)
{
string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
}
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
}
But i am getting error:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
where is my error?
回答1:
You can try the below suggestions:
- Try setting "UseDefaultCredentials" to "False"
smtp.UseDefaultCredentials = false;
- Try logging to your Gmail account, it may be blocking the access.
- Try enabling access to your Gmail account, see this link for more information http://email.about.com/od/gmailtips/qt/How-To-Unlock-Gmail-For-A-New-Email-Program-Or-Service.htm
回答2:
Change "smtp.UseDefaultCredentials = true;" to "smtp.UseDefaultCredentials = false;". Or test your gmail account with code below.
using (MailMessage mm = new MailMessage(new MailAddress("sender@example.com"), new MailAddress("recipient@example.com")))
{
mm.Subject = "test";
mm.Body = "body test";
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
NetworkCredential NetworkCred = new NetworkCredential("sender@example.com", "password");
smtp.UseDefaultCredentials = false;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
}
UPDATE
Go to: google.com/settings/security?hl=en_GB and if field "Access for less secure apps" is Disabled click settings and change it to enabled... Then test your connection with code above. It worked for me on new gmail user
来源:https://stackoverflow.com/questions/25348112/sending-email-using-gmail-from-asp-net