我正在編寫一個C#電子郵件應用程序,目前正在設計用於Gmail,所以我可以測試身份驗證。但是,我收到一個錯誤,這似乎沒有多大意義,因爲我將SSL設置爲true並使用用戶和密碼。身份驗證錯誤發送SMTP請求
錯誤消息: System.Net.Mail.SmtpException:'SMTP服務器需要安全連接或客戶端未通過身份驗證。服務器響應是:5.5.1需要身份驗證。瞭解更多」
using System;
using System.Net;
using System.Net.Mail;
namespace EmailSendingProgram
{
public class EmailSendingClass
{
public static void Main(string[] args)
{
Console.WriteLine("Type your Gmail Address: ");
string from = Console.ReadLine();
Console.WriteLine("Type your Gmail Password: ");
string password = Console.ReadLine();
Console.WriteLine("Type the Email Address you wish to send to: ");
string to = Console.ReadLine();
Console.WriteLine("Type the Subject of the email: ");
string subject = Console.ReadLine();
Console.WriteLine("Type or paste in your email (either text or HTML): ");
string body = Console.ReadLine();
EmailSendingClass email = new EmailSendingClass();
email.Send(from, password, to, subject, body);
}
/// handles sending the email
/// hardcoded to work with gmail just change the CreateSmtpClient from
/// "smtp.gmail.com", 587 to whatever you want to use
public void Send(string from, string password, string to, string subject, string body)
{
var message = CreateMailMessage(from, to, subject, body);
// Host and Port setup for use with Gmail
using (SmtpClient client = CreateSmtpClient("smtp.gmail.com", 587, from, password))
{
client.Send(message);
}
}
/// Defines the SmtpClient for the mail message
/// setups up the network credentials to send the email
private SmtpClient CreateSmtpClient(string host, int port, string from, string password)
{
SmtpClient client = null;
client = new SmtpClient()
{
Host = host,
Port = port,
EnableSsl = true,
Credentials = new NetworkCredential(from, password)
};
return client;
}
/// defines what is contained in the email and where it will be sent
/// also makes all messages send as HTML
private MailMessage CreateMailMessage(string from, string to, string subject, string body)
{
MailMessage message = null;
message = new MailMessage(from, to)
{
Subject = subject,
Body = body
};
message.IsBodyHtml = true;
return message;
}
}
}
我明白有些事情是被錯誤地完成與身份驗證,但我似乎無法找出具體是什麼。所以任何幫助,將不勝感激。
您使用的是什麼端口? – Isma
@Isma他使用587,因爲它顯示在代碼 –
我想這個錯誤是由於gmail的安全規則。如果您沒有禁用該Gmail帳戶的某些安全設置(不記得它是什麼,抱歉),Gmail即使使用正確的憑據和設置也不會讓您的應用程序進行身份驗證。 – ihpar