我正在尝试使用C#中的TCP连接将电子邮件发送到smtp服务器(在此示例中为Google)。 我得到的响应是需要身份验证。
5.5.1需要身份验证。在\ n5.5.1 https://support.google.com/mail/?p=WantAuthError h66sm663716vke.21-gsmtp
中了解更多信息
没有身份验证。我不知道要将电子邮件发送到的帐户的用户名和密码。
我能够找到的所有其他示例都使用预构建的SMTP服务器并构建邮件。
我只希望能够在有人需要重设密码或需要发送系统消息之类的情况下将电子邮件发送到任何电子邮件帐户。
这是我的代码:
TcpClient tcpclient = new TcpClient();
tcpclient.Connect("smtp.gmail.com",465);
//not sure if I need port 465 or 587.
// implicit SSL is always used on SMTP port 465
System.Net.Security.SslStream sslstream = new System.Net.Security.SslStream(tcpclient.GetStream());
sslstream.AuthenticateAsClient("smtp.gmail.com");
writer = new StreamWriter(sslstream);
reader = new StreamReader(sslstream);
string replyText = string.Empty;
string[] capabilities = null;
// read the server's initial greeting
readResponse(220);
// identify myself and get the server's capabilities
if (sendCommand("EHLO myserver.com",ref replyText) == 250)
{
// parse capabilities
capabilities = replyText.Split(new Char[] { '\n' });
}
else
{
// EHLO not supported,have to use HELO instead,but then
// the server's capabilities are unknown...
capabilities = new string[] { };
sendCommand("HELO myserver.com",250);
}
// check for pipelining support... (OPTIONAL!!!)
if (Array.IndexOf(capabilities,"PIpelINING") != -1)
{
// can pipeline...
// send all commands first without reading responses in between
writer.WriteLine("MAIL FROM:<" + "myserver@myserver.com" + ">");
writer.WriteLine("RCPT TO:<" + "anyemail@gmail.com" + ">");
writer.WriteLine("DATA");
writer.Flush();
// now read the responses...
Exception e = null;
// MAIL FROM
int replyCode = readResponse(ref replyText);
if (replyCode != 250)
e = new SmtpCmdFailedException(replyCode,replyText);
// RCPT TO
replyCode = readResponse(ref replyText);
if ((replyCode != 250) && (replyCode != 251) && (e == null))
e = new SmtpCmdFailedException(replyCode,replyText);
// DATA
replyCode = readResponse(ref replyText);
if (replyCode == 354)
{
// DATA accepted,must send email followed by "."
writer.WriteLine("Subject: Email test");
writer.WriteLine("Test 1 2 3");
writer.WriteLine(".");
writer.Flush();
// read the response
replyCode = readResponse(ref replyText);
if ((replyCode != 250) && (e == null))
e = new SmtpCmdFailedException(replyCode,replyText);
}
else
{
// DATA rejected,do not send email
if (e == null)
e = new SmtpCmdFailedException(replyCode,replyText);
}
if (e != null)
{
// if any command failed,reset the session
sendCommand("RSET");
throw e;
}
}
else
{
// not pipelining,MUST read each response before sending the next command...
sendCommand("MAIL FROM:<" + "myserver@myserver.com" + ">",250);
try
{
sendCommand("RCPT TO:<" + "anyemail@gmail.com" + ">",250,251);
sendCommand("DATA",354);
writer.WriteLine("Subject: Email test");
writer.WriteLine("");
writer.WriteLine("Test 1 2 3");
writer.Flush();
sendCommand(".",250);
}
catch (SmtpCmdFailedException e)
{
// if any command failed,reset the session
sendCommand("RSET");
throw;
}
}
// all done
sendCommand("QUIT",221);