SMTP.cs
上传用户:jsz11269
上传日期:2017-01-14
资源大小:450k
文件大小:3k
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Net.Sockets;
- using System.IO;
- namespace SoketEmail
- {
- public class SMTP
- {
- public SMTP() { }
- public bool Send(string strSmtpServer, int nPort, string strSend, string strReceive
- , string strSubject, string strContent)
- {
- string smtpserver = strSmtpServer;// smtp服务器的IP地址
- TcpClient tcpc = new TcpClient();
- try
- {
- tcpc.Connect(smtpserver, nPort);
- StreamReader sr;
- string strCmd;
- sr = new StreamReader(tcpc.GetStream(), Encoding.Default);
- //服务器连接成功以后,首先向服务器发送HeLlo命令
- strCmd = "HELO shaozhd";
- SenSmtpCmd(tcpc, strCmd);
- //然后向服务器发送信件的成员的信箱
- strCmd = "mail from:" + strSend;
- SenSmtpCmd(tcpc, strCmd);
- //向服务器发送收件人的信箱
- strCmd = "rcpt to:" + strReceive;
- SenSmtpCmd(tcpc, strCmd);
- //所有的准备工作都已经作好了,下面开始进行邮件的部分
- strCmd = "data";
- SenSmtpCmd(tcpc, strCmd);
- //邮件内容
- strCmd = "Date: 1234567rn";
- strCmd = strCmd + "From: " + strSend + "rn";
- strCmd = strCmd + "To: " + strReceive + "rn";
- strCmd = strCmd + "Subject: " + strSubject + "rnrn";
- strCmd = strCmd + strContent + "rnrn";
- SenSmtpCmd(tcpc, strCmd);
- strCmd = "rn.rn";
- SenSmtpCmd(tcpc, strCmd);
- //最后 关闭与smtp 服务器的连接
- tcpc.Close();
- return true;
- }
- catch
- {
- return false;
- }
- }
- void SenSmtpCmd(TcpClient tcpc, String strCmd)
- {
- byte[] arrCmd;
- string strRet;
- StreamReader sr;
- Stream s;
- s = tcpc.GetStream();
- strCmd = strCmd + "rn";
- arrCmd = Encoding.Default.GetBytes(strCmd.ToCharArray());
- s = tcpc.GetStream();
- s.Write(arrCmd, 0, strCmd.Length);
- //以下用于程序调试,显示服务器回应信息
- sr = new StreamReader(tcpc.GetStream(), Encoding.Default);
- strRet = sr.ReadLine();
- return;
- }
- }
- }