当前位置:编程学习 > C#/ASP.NET >>

记得原来有人问过用socket实现smtp,这是我的一部分代码

答案:namespace mySmtp
{

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;


    interface ITransport
    {
        void setHost(String smtpHost);
        String getHost();
    
        void setPort(int smtpPort);
        int getPort();
    
        void sendMail(MailMessage msg);
    }


    public class Smtp : ITransport
    {
        private String smtpHost;
        private int smtpPort;
        
        public Smtp()
        {
            //smtpHost = "127.0.0.1";
            //smtpPort = 25;
        }
        
        public Smtp(String host, int port)
        {
            smtpHost = host;
            smtpPort = port;
        }
        
        
        public void setHost(String host)
        {
            smtpHost = host;
        }
        public String getHost()
        {
            return smtpHost;
        }
        
        
        public void setPort(int port)
        {
            smtpPort = port;
        }
        public int getPort()
        {
            return smtpPort;    
        }


        public void sendMail(MailMessage msg)
            
        {
        
            TcpClient tcpc = new TcpClient();

            try
            {
                
                if (smtpHost != null && smtpPort != 0)
                {
                    tcpc.Connect(smtpHost, smtpPort);
                    tcpc.ReceiveTimeout= 20;
                    tcpc.SendTimeout = 20;
                }
                else
                {
                    throw new SmtpException("Cannot use sendMail() method without specifying target host and port");
                }
                
                NetworkStream nwstream = tcpc.GetStream();
                checkForError(ReadFromStream(ref nwstream), SmtpConstants.HELO_REPLY);

                WriteToStream(ref nwstream, "HELO " + smtpHost);
                checkForError(ReadFromStream(ref nwstream), SmtpConstants.OK);

                WriteToStream(ref nwstream, "MAIL FROM: <" + msg.getFrom().getAddress() + ">");
                checkForError(ReadFromStream(ref nwstream), SmtpConstants.OK);

                sendRecipientList(ref nwstream, msg.getTo());
                sendRecipientList(ref nwstream, msg.getCC());
                sendRecipientList(ref nwstream, msg.getBCC());

                WriteToStream(ref nwstream, "DATA");
                checkForError(ReadFromStream(ref nwstream), SmtpConstants.START_INPUT);

                if (msg.getReplyTo() != null)
                {
                    WriteToStream(ref nwstream, "Reply-To: " + msg.getReplyTo().getPersonal() + "<" + msg.getReplyTo().getAddress() + ">;");
                }
                
                if (msg.getFrom() != null)
                {
             &nb

上一个:国外站点上转过来的资料,模拟ping程序
下一个:一个用C#实现的简单http server(转)

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,