⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 smtpserverhelper.cs

📁 c#常用类库大全
💻 CS
📖 第 1 页 / 共 2 页
字号:
                {
                    errmsg += RR;
                }
                errmsg += errstr;
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// 与服务器交互,发送一组命令并接收回应。
    /// </summary>
    private bool Dialog(string[] str, string errstr)
    {
        for (int i = 0; i < str.Length; i++)
        {
            if (!Dialog(str[i], ""))
            {
                errmsg += CRLF;
                errmsg += errstr;
                return false;
            }
        }
        return true;
    }

    /// <summary>
    /// 连接服务器
    /// </summary>
    private bool Connect(string smtpServer, int port)
    {
        try
        {
            tcpClient = new TcpClient(smtpServer, port);
        }
        catch (Exception e)
        {
            errmsg = e.ToString();
            return false;
        }
        networkStream = tcpClient.GetStream();

        if (RightCodeHT[RecvResponse().Substring(0, 3)] == null)
        {
            errmsg = "网络连接失败";
            return false;
        }
        return true;
    }

    /// <summary>
    /// 获取优先级
    /// </summary>
    /// <param name="mailPriority">优先级</param>
    private string GetPriorityString(MailPriority mailPriority)
    {
        string priority = "Normal";
        if (mailPriority == MailPriority.Low)
        {
            priority = "Low";
        }
        else if (mailPriority == MailPriority.High)
        {
            priority = "High";
        }
        return priority;
    }

    /// <summary>
    /// 发送电子邮件
    /// </summary>
    /// <param name="smtpServer">发信SMTP服务器</param>
    /// <param name="port">端口,默认为25</param>
    /// <param name="username">发信人邮箱地址</param>
    /// <param name="password">发信人邮箱密码</param>
    /// <param name="mailMessage">邮件内容</param>
    private bool SendEmail(string smtpServer, int port, bool ESmtp, string username, string password, MailMessage mailMessage)
    {
        if (Connect(smtpServer, port) == false) return false;

        string priority = GetPriorityString(mailMessage.Priority);

        bool Html = (mailMessage.BodyFormat == MailFormat.HTML);

        string[] SendBuffer;
        string SendBufferstr;

        //进行SMTP验证
        if (ESmtp)
        {
            SendBuffer = new String[4];
            SendBuffer[0] = "EHLO " + smtpServer + CRLF;
            SendBuffer[1] = "AUTH LOGIN" + CRLF;
            SendBuffer[2] = Base64Encode(username) + CRLF;
            SendBuffer[3] = Base64Encode(password) + CRLF;
            if (!Dialog(SendBuffer, "SMTP服务器验证失败,请核对用户名和密码。")) return false;
        }
        else
        {
            SendBufferstr = "HELO " + smtpServer + CRLF;
            if (!Dialog(SendBufferstr, "")) return false;
        }

        //发件人地址
        SendBufferstr = "MAIL FROM:<" + username + ">" + CRLF;
        if (!Dialog(SendBufferstr, "发件人地址错误,或不能为空")) return false;

        //收件人地址
        SendBuffer = new string[mailMessage.Recipients.Count];
        for (int i = 0; i < mailMessage.Recipients.Count; i++)
        {
            SendBuffer[i] = "RCPT TO:<" + (string)mailMessage.Recipients[i] + ">" + CRLF;
        }
        if (!Dialog(SendBuffer, "收件人地址有误")) return false;

        SendBufferstr = "DATA" + CRLF;
        if (!Dialog(SendBufferstr, "")) return false;

        //发件人姓名
        SendBufferstr = "From:" + mailMessage.FromName + "<" + mailMessage.From + ">" + CRLF;

        if (mailMessage.Recipients.Count == 0)
        {
            return false;
        }
        else
        {
            SendBufferstr += "To:=?" + mailMessage.Charset.ToUpper() + "?B?" + Base64Encode((string)mailMessage.Recipients[0]) + "?=" + "<" + (string)mailMessage.Recipients[0] + ">" + CRLF;
        }
        SendBufferstr += ((mailMessage.Subject == String.Empty || mailMessage.Subject == null) ? "Subject:" : ((mailMessage.Charset == "") ? ("Subject:" + mailMessage.Subject) : ("Subject:" + "=?" + mailMessage.Charset.ToUpper() + "?B?" + Base64Encode(mailMessage.Subject) + "?="))) + CRLF;
        SendBufferstr += "X-Priority:" + priority + CRLF;
        SendBufferstr += "X-MSMail-Priority:" + priority + CRLF;
        SendBufferstr += "Importance:" + priority + CRLF;
        SendBufferstr += "X-Mailer: Lion.Web.Mail.SmtpMail Pubclass [cn]" + CRLF;
        SendBufferstr += "MIME-Version: 1.0" + CRLF;
        if (mailMessage.Attachments.Count != 0)
        {
            SendBufferstr += "Content-Type: multipart/mixed;" + CRLF;
            SendBufferstr += " boundary=\"=====" + (Html ? "001_Dragon520636771063_" : "001_Dragon303406132050_") + "=====\"" + CRLF + CRLF;
        }
        if (Html)
        {
            if (mailMessage.Attachments.Count == 0)
            {
                SendBufferstr += "Content-Type: multipart/alternative;" + CRLF; //内容格式和分隔符
                SendBufferstr += " boundary=\"=====003_Dragon520636771063_=====\"" + CRLF + CRLF;
                SendBufferstr += "This is a multi-part message in MIME format." + CRLF + CRLF;
            }
            else
            {
                SendBufferstr += "This is a multi-part message in MIME format." + CRLF + CRLF;
                SendBufferstr += "--=====001_Dragon520636771063_=====" + CRLF;
                SendBufferstr += "Content-Type: multipart/alternative;" + CRLF; //内容格式和分隔符
                SendBufferstr += " boundary=\"=====003_Dragon520636771063_=====\"" + CRLF + CRLF;
            }
            SendBufferstr += "--=====003_Dragon520636771063_=====" + CRLF;
            SendBufferstr += "Content-Type: text/plain;" + CRLF;
            SendBufferstr += ((mailMessage.Charset == "") ? (" charset=\"iso-8859-1\"") : (" charset=\"" + mailMessage.Charset.ToLower() + "\"")) + CRLF;
            SendBufferstr += "Content-Transfer-Encoding: base64" + CRLF + CRLF;
            SendBufferstr += Base64Encode("邮件内容为HTML格式,请选择HTML方式查看") + CRLF + CRLF;

            SendBufferstr += "--=====003_Dragon520636771063_=====" + CRLF;

            SendBufferstr += "Content-Type: text/html;" + CRLF;
            SendBufferstr += ((mailMessage.Charset == "") ? (" charset=\"iso-8859-1\"") : (" charset=\"" + mailMessage.Charset.ToLower() + "\"")) + CRLF;
            SendBufferstr += "Content-Transfer-Encoding: base64" + CRLF + CRLF;
            SendBufferstr += Base64Encode(mailMessage.Body) + CRLF + CRLF;
            SendBufferstr += "--=====003_Dragon520636771063_=====--" + CRLF;
        }
        else
        {
            if (mailMessage.Attachments.Count != 0)
            {
                SendBufferstr += "--=====001_Dragon303406132050_=====" + CRLF;
            }
            SendBufferstr += "Content-Type: text/plain;" + CRLF;
            SendBufferstr += ((mailMessage.Charset == "") ? (" charset=\"iso-8859-1\"") : (" charset=\"" + mailMessage.Charset.ToLower() + "\"")) + CRLF;
            SendBufferstr += "Content-Transfer-Encoding: base64" + CRLF + CRLF;
            SendBufferstr += Base64Encode(mailMessage.Body) + CRLF;
        }
        if (mailMessage.Attachments.Count != 0)
        {
            for (int i = 0; i < mailMessage.Attachments.Count; i++)
            {
                string filepath = (string)mailMessage.Attachments[i];
                SendBufferstr += "--=====" + (Html ? "001_Dragon520636771063_" : "001_Dragon303406132050_") + "=====" + CRLF;
                SendBufferstr += "Content-Type: text/plain;" + CRLF;
                SendBufferstr += " name=\"=?" + mailMessage.Charset.ToUpper() + "?B?" + Base64Encode(filepath.Substring(filepath.LastIndexOf("\\") + 1)) + "?=\"" + CRLF;
                SendBufferstr += "Content-Transfer-Encoding: base64" + CRLF;
                SendBufferstr += "Content-Disposition: attachment;" + CRLF;
                SendBufferstr += " filename=\"=?" + mailMessage.Charset.ToUpper() + "?B?" + Base64Encode(filepath.Substring(filepath.LastIndexOf("\\") + 1)) + "?=\"" + CRLF + CRLF;
                SendBufferstr += GetStream(filepath) + CRLF + CRLF;
            }
            SendBufferstr += "--=====" + (Html ? "001_Dragon520636771063_" : "001_Dragon303406132050_") + "=====--" + CRLF + CRLF;
        }
        SendBufferstr += CRLF + "." + CRLF;
        if (!Dialog(SendBufferstr, "错误信件信息")) return false;

        SendBufferstr = "QUIT" + CRLF;
        if (!Dialog(SendBufferstr, "断开连接时错误")) return false;

        networkStream.Close();
        tcpClient.Close();
        return true;
    }
    #endregion

    #region 公有方法
    /// <summary>
    /// 发送电子邮件,SMTP服务器不需要身份验证
    /// </summary>
    /// <param name="smtpServer">发信SMTP服务器</param>
    /// <param name="port">端口,默认为25</param>
    /// <param name="mailMessage">邮件内容</param>
    public bool SendEmail(string smtpServer, int port, MailMessage mailMessage)
    {
        return SendEmail(smtpServer, port, false, "", "", mailMessage);
    }

    /// <summary>
    /// 发送电子邮件,SMTP服务器需要身份验证
    /// </summary>
    /// <param name="smtpServer">发信SMTP服务器</param>
    /// <param name="port">端口,默认为25</param>
    /// <param name="username">发信人邮箱地址</param>
    /// <param name="password">发信人邮箱密码</param>
    /// <param name="mailMessage">邮件内容</param>
    public bool SendEmail(string smtpServer, int port, string username, string password, MailMessage mailMessage)
    {
        return SendEmail(smtpServer, port, true, username, password, mailMessage);
    }
    #endregion
}

/// <summary>
/// 发送邮件
/// </summary>
//--------------------调用-----------------------
//MailAttachments ma=new MailAttachments();
//ma.Add(@"附件地址");
//MailMessage mail = new MailMessage();
//mail.Attachments=ma;
//mail.Body="你好";
//mail.AddRecipients("zjy99684268@163.com");
//mail.From="zjy99684268@163.com";
//mail.FromName="zjy";
//mail.Subject="Hello";
//SmtpClient sp = new SmtpClient();
//sp.SmtpServer = "smtp.163.com";
//sp.Send(mail, "zjy99684268@163.com", "123456");
//------------------------------------------------
public class SmtpClient
{
    #region 构造函数
    public SmtpClient()
    {}

    public SmtpClient(string _smtpServer)
    {
        _SmtpServer = _smtpServer;
    }
    #endregion

    #region 私有字段
    private string errmsg;
    private string _SmtpServer;
    #endregion

    #region 公有属性
    /// <summary>
    /// 错误消息反馈
    /// </summary>
    public string ErrMsg
    {
        get { return errmsg; }
    }

    /// <summary>
    /// 邮件服务器
    /// </summary>
    public string SmtpServer
    {
        set { _SmtpServer = value; }
        get { return _SmtpServer; }
    }
    #endregion

    public bool Send(MailMessage mailMessage, string username, string password)
    {
        SmtpServerHelper helper = new SmtpServerHelper();
        if (helper.SendEmail(_SmtpServer, 25, username, password, mailMessage))
            return true;
        else
        {
            errmsg = helper.ErrMsg;
            return false;
        }
    }
}

/// <summary>
/// 操作服务器上邮件
/// </summary>
public class SmtpMail
{
    public SmtpMail()
    { }

    #region 字段
    private StreamReader sr;
    private StreamWriter sw;
    private TcpClient tcpClient;
    private NetworkStream networkStream;
    #endregion

    #region 私有方法
    /// <summary>
    /// 向服务器发送信息
    /// </summary>
    private bool SendDataToServer(string str)
    {
        try
        {
            sw.WriteLine(str);
            sw.Flush();
            return true;
        }
        catch (Exception err)
        {
            return false;
        }
    }

    /// <summary>
    /// 从网络流中读取服务器回送的信息
    /// </summary>
    private string ReadDataFromServer()
    {
        string str = null;
        try
        {
            str = sr.ReadLine();
            if (str[0] == '-')
            {
                str = null;
            }
        }
        catch (Exception err)
        {
            str = err.Message;
        }
        return str;
    }
    #endregion

    #region 获取邮件信息
    /// <summary>
    /// 获取邮件信息
    /// </summary>
    /// <param name="uid">邮箱账号</param>
    /// <param name="pwd">邮箱密码</param>
    /// <returns>邮件信息</returns>
    public ArrayList ReceiveMail(string uid, string pwd)
    {
        ArrayList EmailMes = new ArrayList();
        string str;
        int index = uid.IndexOf('@');
        string pop3Server = "pop3." + uid.Substring(index + 1);
        tcpClient = new TcpClient(pop3Server, 110);
        networkStream = tcpClient.GetStream();
        sr = new StreamReader(networkStream);
        sw = new StreamWriter(networkStream);

        if (ReadDataFromServer() == null) return EmailMes;
        if (SendDataToServer("USER " + uid) == false) return EmailMes;
        if (ReadDataFromServer() == null) return EmailMes;
        if (SendDataToServer("PASS " + pwd) == false) return EmailMes;
        if (ReadDataFromServer() == null) return EmailMes;
        if (SendDataToServer("LIST") == false) return EmailMes;
        if ((str = ReadDataFromServer()) == null) return EmailMes;

        string[] splitString = str.Split(' ');
        int count = int.Parse(splitString[1]);
        if (count > 0)
        {
            for (int i = 0; i < count; i++)
            {
                if ((str = ReadDataFromServer()) == null) return EmailMes;
                splitString = str.Split(' ');
                EmailMes.Add(string.Format("第{0}封邮件,{1}字节", splitString[0], splitString[1]));
            }
            return EmailMes;
        }
        else
        {
            return EmailMes;
        }
    }
    #endregion

    #region 读取邮件内容
    /// <summary>
    /// 读取邮件内容
    /// </summary>
    /// <param name="mailMessage">第几封</param>
    /// <returns>内容</returns>
    public string ReadEmail(string str)
    {
        string state = "";
        if (SendDataToServer("RETR " + str) == false)
            state = "Error";
        else
        {
            state = sr.ReadToEnd();
        }
        return state;
    }
    #endregion

    #region 删除邮件
    /// <summary>
    /// 删除邮件
    /// </summary>
    /// <param name="str">第几封</param>
    /// <returns>操作信息</returns>
    public string DeleteEmail(string str)
    {
        string state = "";
        if (SendDataToServer("DELE " + str) == true)
        {
            state = "成功删除";
        }
        else
        {
            state = "Error";
        }
        return state;
    }
    #endregion

    #region 关闭服务器连接
    /// <summary>
    /// 关闭服务器连接
    /// </summary>
    public void CloseConnection()
    {
        SendDataToServer("QUIT");
        sr.Close();
        sw.Close();
        networkStream.Close();
        tcpClient.Close();
    }
    #endregion
}



⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -