sending email using gmail from asp.net

谁说胖子不能爱 提交于 2019-12-11 10:48:15

问题


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:

  1. Try setting "UseDefaultCredentials" to "False" smtp.UseDefaultCredentials = false;
  2. Try logging to your Gmail account, it may be blocking the access.
  3. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!