Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

c# - mail sending with network credential as true in windows form not working

I want to do an application for sending emails in C# windows application.I used smtp server,but I don't want to set the network credentials. So I set it as true.but 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

Here is the code:

SmtpClient oClient = new SmtpClient();
oClient.Host = "smtp.gmail.com";
oClient.Port = 25;
oClient.UseDefaultCredentials = true;
oClient.Credentials = new System.Net.NetworkCredential();
oClient.EnableSsl = true;
MailMessage oMail = new MailMessage();
oMail.To.Add(txtTo.Text.Trim());
oMail.From = new MailAddress("[email protected]");
oMail.Subject = txtSubject.Text;
oMail.Body = txtBody.Text;
oMail.IsBodyHtml = true;
oClient.Send(oMail);
MessageBox.Show("Mail Send");

here I set the host as gmail.com,I need to send and receive mails using all email service providers.So how can I set the host and port?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

gmail uses port 587

oClient.Port = 587;

You may also want to set UseDefaultCredentials to false and explicitly declare username and password. By declaring it to be true, you are trying to log into your gmail account using your windows credentials.

oClient.UseDefaultCredentials = false;
oClient.Credentials = new NetworkCredential("[email protected]", "password");

Also, in gmail security, you will need to allow Less Secure Applications.

Finally, you need to change how your Mail.To is populated:

oMail.To.Add(new MailAddress(txtTo.Text.Trim()));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...