用户登录  |  用户注册
首 页商业源码原创产品编程论坛
当前位置:PB创新网文章中心.Net

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

减小字体 增大字体 作者:佚名  来源:本站整理  发布时间:2009-03-16 15:55:51
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)
                {
                    WriteToStream(ref nwstream, "From: " + msg.getFrom().getPersonal() + "<" + msg.getFrom().getAddress() + ">;");
                }
                
                
                WriteToStream(ref nwstream, "Subject: " + msg.getSubject());
                WriteToStream(ref nwstream, "To: " + createAddressList(msg.getTo()));
                WriteToStream(ref nwstream, "CC: " + createAddressList(msg.getCC()));

                if (msg.getPriority() != null)
                {
                    WriteToStream(ref nwstream, "X-Priority: " + msg.getPriority());
                }
                //WriteToStream(ref nwstream, "Return-Path:" + msg.getFrom().getAddress());

                WriteToStream(ref nwstream, msg.getBody());
                WriteToStream(ref nwstream, "\r\n.\r\n");
                checkForError(ReadFromStream(ref nwstream), SmtpConstants.OK);


                
                /*
                WriteToStream(ref nwstream, "QUIT");
                checkForError(ReadFromStream(ref nwstream), SmtpConstants.UNKNOWN);
                */

            }
            catch(SocketException e)
            {

                throw new SmtpException("Cannot connect to specified smtp host(" + smtpHost + ":" + smtpPort + ").", e);

            }
            finally
            {
                tcpc.Close();
            }
        }
        
        
        
                private String createAddressList(ArrayList msgList)
        {
            StringBuilder sb = new StringBuilder();

            for (IEnumerator i = msgList.GetEnumerator(); i.MoveNext();)
            {
                Address a = (Address)i.Current;
                string address = a.getPersonal() + "<" + a.getAddress() + ">;";
                sb.Append(a.getPersonal() + "<" + a.getAddress() + ">;");
            }        
            
            return sb.ToString();
        }
        
        private void sendRecipientList(ref NetworkStream nwstream, ArrayList recipients)
        {
                    for (IEnumerator i = recipients.GetEnumerator();i.MoveNext();)
            {
                Address recipient = (Address)i.Current;
                String address = recipient.getAddress();

                // potential 501 error (not valid sender) below:
                WriteToStream(ref nwstream, "RCPT TO: <" + address + ">");
                checkForError(ReadFromStream(ref nwstream), SmtpConstants.OK);
            }    
        }

        private bool checkMailMessage(MailMessage message)
        {
            String returnMessage = "Mail Message is missing ";
        
            if (message.getTo() == null)
                throw new SmtpException(returnMessage + "''To:'' field");
                        
            
            else if(message.getFrom() == null)
                throw new SmtpException(returnMessage + "''From:'' field");
            else if(message.getSubject() == null)
                throw new SmtpException(returnMessage + "Subject");
            else if(message.getBody() == null)
                throw new SmtpException(returnMessage + "Body");
            */
            
            else
                return true;
        }

                private void WriteToStream(ref NetworkStream nw, string line)
        {
            
            string stringToSend = line + "\r\n";

            Byte[] arrToSend = Encoding.ASCII.GetBytes(stringToSend.ToCharArray());
            nw.Write(arrToSend, 0, arrToSend.Length);
        }

        private String ReadFromStream(ref NetworkStream nw)
        {
            byte[] readBuffer = new byte[512];
            int length = nw.Read(readBuffer, 0, readBuffer.Length);
            String returnMsg = Encoding.ASCII.GetString(readBuffer, 0, length);

            return returnMsg;
        }


        /**
         *
         * Checks stream returned from SMTP server for success code
         * If the success code is not present it will throw an error.        
         *
         */
        private void checkForError(String s, String successCode)
        {
            if (s.IndexOf(successCode) == -1)
                throw new SmtpException("ERROR - Expecting " + successCode + ". Recieved: " + s);
        }

    }
    
}

Tags:

作者:佚名

文章评论评论内容只代表网友观点,与本站立场无关!

   评论摘要(共 0 条,得分 0 分,平均 0 分) 查看完整评论
PB创新网ourmis.com】Copyright © 2000-2009 . All Rights Reserved .
页面执行时间:4,140.62500 毫秒
Email:ourmis@126.com QQ:2322888 蜀ICP备05006790号