我创建了一个用于发送电子邮件的Windows应用程序。我已经给了证书。 我开启了google / settings / lesssecure应用。尽管它没有发送。它显示错误 SMTP服务器需要安全连接或客户端未经过身份验证。服务器响应是:5.5.1需要身份验证这是我的代码。
MailMessage message = new MailMessage();
message.From = new MailAddress("Selvacsebe23@gmail.com");
string[] mailaddress = new string[count];
int i;
if (textSubject.Text != string.Empty)
{
message.Subject = textSubject.Text;
if (textBody.Text != string.Empty)
{
message.To="Selvakesavan@gmail.com"
message.IsBodyHtml = true;
string tmpBody = "Hello " + "," + "<br/> <br/>" + textBody.Text + "<br/> <br/>" + "Thanks and Regardds";
message.Body = tmpBody;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = true;
client.Host = "smtp.gmail.com";
client.Port = 587;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("selvacsebe23@gmail.com", "mypassword");
message.Priority = MailPriority.High;
client.EnableSsl = true;
client.Send(message);
MessageBox.Show("Mail has sent successfully !!!", "Success !");
}
else
{
MessageBox.Show("Please Enter Body of the Message !");
}
}
else
{
MessageBox.Show("Please Enter Subject !");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Failure !");
log.Fatal(ex.Message);
}
}
答案 0 :(得分:1)
如果您启用两步验证,则需要使用应用专用密码进行登录。你可以在这里创建它: https://support.google.com/accounts/answer/185833?hl=en。如果您使用普通密码,则会出现例外: 5.5.1需要验证。您不需要大量代码,此代码足以发送没有附件的电子邮件:
const string from = "user1@gmail.com";
const string to = "user2@yahoo.com";
const string subject = "This is subject";
const string body = "This is body";
const string appSpecificPassword = "akdfkajsdhklakdfh";
var mailMessage = new MailMessage(from, to, subject, body);
using (var smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
smtpClient.EnableSsl = true;
smtpClient.Credentials = new NetworkCredential(from, appSpecificPassword);
smtpClient.Send(mailMessage);
}