Я пишу приложение, которое проверяет адреса электронной почты, для одной части этого мне нужно отправить небольшой объем данных на адрес электронной почты, чтобы полностью его проверить, в настоящее время я использую сокеты, чтобы это выполнить.C# SMTP Проблемы с сокетами
В то время как я тестировал, я использовал SMTP-сервер друзей для тестирования, и мой сокет работал нормально, но когда я пробовал то же самое на большом почтовом провайдере (gmail, hotmail и т. Д.), У него не было ничего.
Теперь я пришел к выводу, что это проверка подлинности и безопасности, поэтому я протестировал отправку сообщения в gmail с использованием .Nets, построенных в SmtpClient и различных почтовых объектах с использованием SslEnabled, и предоставления ему учетных данных, которые он просил, работать.
Что мне нужно выполнить это:
посылает эти данные без необходимости предоставить данные для входа чисто актерские как обмен. - также средство для защиты Ssl в моем сокете.
Любая помощь с любым из этого была бы замечательной и полезной! Код ниже ...
/// <summary>
/// Opens up the socket and begins trying to connect to the provided domain
/// </summary>
/// <param name="domain">The domain listening on SMTP ports</param>
/// <param name="recipient">The email recipient</param>
/// <returns>Bool verifying success</returns>
public static bool ActivateSocket(string domain, string recipient)
{
//X509Certificate cert = new X509Certificate();
//Prepare our first command
string SMTPcommand = "HELO www.codegremlin.co.uk\r\n";
Encoding ASCII = Encoding.ASCII;
//convert to byte array and get the buffers ready
Byte[] ByteCommand = ASCII.GetBytes(SMTPcommand);
Byte[] RecvResponseCode = new Byte[3];
Byte[] RecvFullMessage = new Byte[256];
//method response value
bool TransactionSuccess = false;
try
{
// do all of this outside so its fresh after every iteration
Socket s = null;
IPEndPoint hostEndPoint;
IPAddress hostAddress = null;
int conPort = 587;
// get all the ip's assosciated with the domain
IPHostEntry hostInfo = Dns.GetHostEntry(domain);
IPAddress[] IPaddresses = hostInfo.AddressList;
// go through each ip and attempt a connection
for (int index = 0; index < IPaddresses.Length; index++)
{
hostAddress = IPaddresses[index];
// get our end point
hostEndPoint = new IPEndPoint(hostAddress, conPort);
// prepare the socket
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.ReceiveTimeout = 2000;
s.SendTimeout = 4000;
try { s.Connect(hostEndPoint); }
catch { Console.WriteLine("Connection timed out..."); }
if (!s.Connected)
{
// Connection failed, try next IPaddress.
TransactionSuccess = false;
s = null;
continue;
}
else
{
// im going through the send mail, SMTP proccess here, slightly incorrectly but it
//is enough to promote a response from the server
s.Receive(RecvFullMessage);
Console.WriteLine(ASCII.GetString(RecvFullMessage));
s.Send(ByteCommand, ByteCommand.Length, 0);
s.Receive(RecvFullMessage);
Console.WriteLine(ASCII.GetString(RecvFullMessage));
ByteCommand = ASCII.GetBytes("MAIL FROM:[email protected]\r\n");
s.Send(ByteCommand, ByteCommand.Length, 0);
s.Receive(RecvFullMessage);
Console.WriteLine(ASCII.GetString(RecvFullMessage));
ByteCommand = ASCII.GetBytes("RCPT TO:[email protected]\r\n");
s.Send(ByteCommand, ByteCommand.Length, 0);
s.Receive(RecvFullMessage);
Console.WriteLine(ASCII.GetString(RecvFullMessage));
ByteCommand = ASCII.GetBytes("DATA\r\n");
s.Send(ByteCommand, ByteCommand.Length, 0);
s.Receive(RecvFullMessage);
Console.WriteLine(ASCII.GetString(RecvFullMessage));
ByteCommand = ASCII.GetBytes("this email was sent as a test!\r\n.\r\n");
s.Send(ByteCommand, ByteCommand.Length, 0);
s.Receive(RecvFullMessage);
Console.WriteLine(ASCII.GetString(RecvFullMessage));
ByteCommand = ASCII.GetBytes("SEND\r\n");
s.Send(ByteCommand, ByteCommand.Length, 0);
s.Receive(RecvFullMessage);
Console.WriteLine(ASCII.GetString(RecvFullMessage));
ByteCommand = ASCII.GetBytes("QUIT\r\n");
s.Send(ByteCommand, ByteCommand.Length, 0);
s.Receive(RecvFullMessage);
Console.WriteLine(ASCII.GetString(RecvFullMessage));
int i = 0;
TransactionSuccess = true;
}
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch (NullReferenceException e)
{
Console.WriteLine("NullReferenceException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch (Exception e)
{
Console.WriteLine("Exception caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
return TransactionSuccess;
}
Извините, удалил сообщение, поскольку оно было неточным. Спасибо за исправления, @Daniel A. White и @Storm – David
Привет, в чем смысл этого кода? Это похоже на скруббер списка рассылки для целей спама. В любом случае, я предлагаю вам посмотреть на ошибку, которую вы получаете с сервера, с которым вы подключаетесь, и получить от этого решение. Без четкого указания проблемы трудно предложить решения. – Lazarus
Цель - чистое подтверждение электронной почты, im на хорошей стороне войны на спаме: P – DevlopingTheNextGen