在.net中支持ESMTP身份验证的邮件发送简单讲解

 
下面是一个简单的示例:(没有做任何判断与封装,仅供参考)
 
代码
 
string smtp = "mail.com";
 
string from = "[email protected]";
 
string pwd = "pwd";
 
string to = "[email protected]";
 
//建立链接
 
TcpClient tc = new TcpClient(smtp,25);
 
byte[] b = new byte[1024];
 
tc.GetStream().Read(b,0,b.Length);
 
Response.Write(Encoding.UTF8.GetString(b)+"<br/>");
 
//标识身份
 
WriteMsg(tc.GetStream(), "HELO xxxx\r\n");
 
Response.Write(ReadMsg(tc.GetStream()) + "<br/>");
 
//身份验证开始
 
WriteMsg(tc.GetStream(), "AUTH LOGIN\r\n");
 
Response.Write(ReadMsg(tc.GetStream()) + "<br/>");
 
//帐号 base64编码
 
byte[] bTxt=new byte[1024];
 
bTxt=Encoding.UTF8.GetBytes(from);
 
WriteMsg(tc.GetStream(), Convert.ToBase64String(bTxt)+"\r\n");
 
Response.Write(ReadMsg(tc.GetStream()) + "<br/>");
 
//密码base64编码
 
bTxt=Encoding.UTF8.GetBytes(pwd);
 
WriteMsg(tc.GetStream(), Convert.ToBase64String(bTxt) + "\r\n");
 
Response.Write(ReadMsg(tc.GetStream()) + "<br/>");
 
//身份验证结束
 
//发送邮件地址
 
WriteMsg(tc.GetStream(), string.Format("MAIL FROM:{0}\r\n", from));
 
Response.Write(ReadMsg(tc.GetStream()) + "<br/>");
 
//接受邮件地址,可以有多个RCPT TO
 
WriteMsg(tc.GetStream(), string.Format("RCPT TO:{0}\r\n", to));
 
Response.Write(ReadMsg(tc.GetStream()) + "<br/>");
 
//初如化
 
WriteMsg(tc.GetStream(), "DATA \r\n");
 
Response.Write(ReadMsg(tc.GetStream()) + "<br/>");
 
//邮件内容
 
StringBuilder sb = new StringBuilder();
 
sb.AppendFormat("From:{0}\r\n", from);//发信人

sb.AppendFormat("To:{0}\r\n", to);//收信人,可以有多个,用分号隔开, 这两行可以与上面的MAIL FROM和RCPT TO不同(显示在邮件内容里的)
 
sb.AppendFormat("Date:{0}\r\n",DateTime.Now.ToString());//时间
 
sb.AppendFormat("Subject:{0}\r\n", "测试");//主题
 
sb.Append("\r\n");
 
sb.Append("内容"); //正文
 
sb.Append("\r\n.\r\n");
 
WriteMsg(tc.GetStream(), sb.ToString());
 
Response.Write(ReadMsg(tc.GetStream()) + "<br/>");
 
//结束会话
 
WriteMsg(tc.GetStream(), "QUIT");
 
//关闭链接
 
tc.Close();
 
如果运行正常,上面的返回状态依次为:
 
220 mail.com ESMTP CMailServer 5.4.6 SMTP Service Ready
 
250 welcome here
 
334 VXNlcm5hbWU6
 
334 UGFzc3dvcmQ6
 
235 OK
 
250 OK
 
250 OK
 
354 send the mail data, end with .
 
250 OK

 

你可能感兴趣的:(.net)