SMTP.cs
上传用户:jsz11269
上传日期:2017-01-14
资源大小:450k
文件大小:3k
源码类别:

Email服务器

开发平台:

C#

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net.Sockets;
  5. using System.IO;
  6. namespace SoketEmail
  7. {
  8.     public class SMTP
  9.     {
  10.         public SMTP() { }
  11.         public bool Send(string strSmtpServer, int nPort, string strSend, string strReceive
  12.             , string strSubject, string strContent)
  13.         {
  14.             string smtpserver = strSmtpServer;// smtp服务器的IP地址
  15.             TcpClient tcpc = new TcpClient();
  16.             try
  17.             {
  18.                 tcpc.Connect(smtpserver, nPort);
  19.                 StreamReader sr;
  20.                 string strCmd;
  21.                 sr = new StreamReader(tcpc.GetStream(), Encoding.Default);
  22.                 //服务器连接成功以后,首先向服务器发送HeLlo命令
  23.                 strCmd = "HELO shaozhd";
  24.                 SenSmtpCmd(tcpc, strCmd);
  25.                 //然后向服务器发送信件的成员的信箱
  26.                 strCmd = "mail from:" + strSend;
  27.                 SenSmtpCmd(tcpc, strCmd);
  28.                 //向服务器发送收件人的信箱
  29.                 strCmd = "rcpt to:" + strReceive;
  30.                 SenSmtpCmd(tcpc, strCmd);
  31.                 //所有的准备工作都已经作好了,下面开始进行邮件的部分
  32.                 strCmd = "data";
  33.                 SenSmtpCmd(tcpc, strCmd);
  34.                 //邮件内容
  35.                 strCmd = "Date: 1234567rn";
  36.                 strCmd = strCmd + "From: " + strSend + "rn";
  37.                 strCmd = strCmd + "To: " + strReceive + "rn";
  38.                 strCmd = strCmd + "Subject: " + strSubject + "rnrn";
  39.                 strCmd = strCmd + strContent + "rnrn";
  40.                 SenSmtpCmd(tcpc, strCmd);
  41.                 strCmd = "rn.rn";
  42.                 SenSmtpCmd(tcpc, strCmd);
  43.                 //最后 关闭与smtp 服务器的连接
  44.                 tcpc.Close();
  45.                 return true;
  46.             }
  47.             catch
  48.             {
  49.                 return false;
  50.             }
  51.         }
  52.         void SenSmtpCmd(TcpClient tcpc, String strCmd)
  53.         {
  54.             byte[] arrCmd;
  55.             string strRet;
  56.             StreamReader sr;
  57.             Stream s;
  58.             s = tcpc.GetStream();
  59.             strCmd = strCmd + "rn";
  60.             arrCmd = Encoding.Default.GetBytes(strCmd.ToCharArray());
  61.             s = tcpc.GetStream();
  62.             s.Write(arrCmd, 0, strCmd.Length);
  63.             //以下用于程序调试,显示服务器回应信息
  64.             sr = new StreamReader(tcpc.GetStream(), Encoding.Default);
  65.             strRet = sr.ReadLine();
  66.             return;
  67.         }
  68.     }
  69. }