c#發送Email方法整理

来源:互联网 发布:java.util.base64加密 编辑:程序博客网 时间:2024/05/22 09:40

        //EmailInfoTB
        private int ms_paranums;            //EMail的主題的參數個數
        private string ms_Subject;   //EMail的主題
        private string ms_From;    //EMail的發送者,這裡填寫公司管理者郵箱
        private string ms_To;    //EMail的接收者
        private string ms_CC;    //抄送者
        private string ms_BCC;    //加密抄送
        private string ms_Body;    //EMail的內容
        private string ms_Attachment;  //EMail的附檔路徑
        private string ms_BodyFormat;  //內容格式(純文字/HTML)
        private string ms_BodyEncoding;  //內容的編碼方式
        private string ms_Headers;   //自訂標頭
        private string ms_UrlContentBase; //
        private string ms_UrlContentLocation;//
        private string ms_Priority;   //EMail的優先權設定
        private bool mb_Authenticate = true;//是否需要鑒別

        //EmailSmtpTB
        private string ms_SendUserName;  //發送者郵件的用戶名
        private string ms_SendPassword;  //發送者郵件的密碼
        private string ms_SmtpServer;  //EMail的SMTP服務者IP,這裡填寫  
        private string ms_SmtpAuthenticate; //SMTP验证选项:  匿名验证(NONE) 0 , 普通验证(Basic (Base64 encoded)) 1 ,NTLM 验证(NTLM) 2
        private string ms_SmtpUseSsl;       //'是否使用套接字SSL true/false
        private string ms_SmtpServerPort;   //'smtp默認端口 25 ,如果使用SSL則默認為465
        private string ms_SendUsing;        //'1 代表使用 local smtp, 2 為外部 smtp

        public string mStrSysName = "";

 

/// <summary>
        /// 發送密碼給使用者email
        /// </summary>
        /// <param name="strUserName"></param>
        /// <param name="strUserPw"></param>
        /// <param name="strMailTo"></param>
        /// <returns></returns>
        public Boolean SendPasswordToUser(string strUserName, string strUserPw, string strMailTo, string strUrl, string pHospNo)
        {
            try
            {
                if(this.mStrSysName=="")//同時發送多封電郵時,不用每次都讀取一次系統名稱
                    this.mStrSysName = "";//系統名稱
                string strSubject = "";
                string strBody = "";                 
                strBody = this.GetEmailBodyCn(this.mStrSysName, strUserName, strUserPw, strMailTo, strUrl);
                        strSubject = " 忘记密码";
                strSubject = this.mStrSysName + strSubject;
                this.To = strMailTo;
                this.Subject = strSubject;
                this.Body = strBody;
                this.sendMail();
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private string GetEmailBodyCn(string pSysName, string pUserName, string pUserPW, string strMailTo, string strUrl)
        {
            string strSpace = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
            StringBuilder sbMail = new StringBuilder();
            sbMail.AppendLine(pUserName + " 您好:<br>");
            sbMail.Append(strSpace + "以下是向您发送登录 " + pSysName + " 系统的密码");
            if (strUrl != "")
                sbMail.Append("(<a href='#' onclick='window.open(\"" + strUrl + "\");'>" + strUrl.Replace("/Login.aspx", "") + "</a>)");
            sbMail.Append(".<br>");
            sbMail.AppendLine(strSpace + strSpace + "登录帳号: " + strMailTo + "<br>");
            sbMail.AppendLine(strSpace + strSpace + "登录密码: " + pUserPW + "<br>");
            sbMail.AppendLine("-----------------------------------------------------<br>");
            sbMail.AppendLine("这封电子邮件是由 " + pSysName + " 系统自动发送的, 请不要回复;您记住登录密码后,请删除本电子邮件,谢谢! <br>");

            return sbMail.ToString();
        }

public void sendMail()
        {
            try
            {
                System.Net.Mail.MailMessage o_mm = new MailMessage();

                o_mm.Subject = this.ms_Subject;
                o_mm.From = new MailAddress(this.ms_From);
                o_mm.To.Add(new MailAddress(this.ms_To));
                if (this.ms_CC != "")
                {
                    o_mm.CC.Add(new MailAddress(this.ms_CC));
                }
                if (this.ms_BCC != "")
                {
                    o_mm.Bcc.Add(new MailAddress(this.ms_BCC));
                }
                o_mm.Body = HtmlToStr(this.ms_Body);//"<img src=\"cid:\">"

                //添加郵件
                if (this.ms_Attachment != null && !this.ms_Attachment.Equals(string.Empty))
                {
                    Attachment mailAttach = new Attachment(this.ms_Attachment);
                    o_mm.Attachments.Add(mailAttach);
                }
                if (this.ms_BodyFormat.Equals("text"))
                {
                    o_mm.IsBodyHtml = false;
                }
                else
                {
                    o_mm.IsBodyHtml = true;//添加圖片Log
                    //AlternateView htmlBody = AlternateView.CreateAlternateViewFromString("<img src=\"" + System.Web.Configuration.WebConfigurationManager.ConnectionStrings["APWChttpLink"].ConnectionString + "/IMAGES/LOGO.jpg\"><br/>" + this.ms_Body, null, "text/html");
                    AlternateView htmlBody = AlternateView.CreateAlternateViewFromString( this.ms_Body, null, "text/html");
                    o_mm.AlternateViews.Add(htmlBody);
                }
                //郵件發送失敗則告知
                o_mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

                switch (this.ms_BodyEncoding.ToLower())
                {
                    case "big5": o_mm.BodyEncoding = System.Text.Encoding.GetEncoding("Big5");
                        break;
                    case "gb2312": o_mm.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");
                        break;
                    default:
                        o_mm.BodyEncoding = System.Text.Encoding.UTF8;
                        break;
                }
                //設置郵件優先級

                switch (this.ms_Priority)
                {
                    case "Normal": o_mm.Priority = MailPriority.Normal;
                        break;
                    case "Low": o_mm.Priority = MailPriority.Low;
                        break;
                    default:
                        o_mm.Priority = MailPriority.High;
                        break;
                }
                SmtpClient smtp = new SmtpClient();
                smtp.Host = this.ms_SmtpServer;     //郵件服務器
                smtp.Port = int.Parse(this.ms_SmtpServerPort); //端口號
                smtp.UseDefaultCredentials = false; //是否使用本地驗證

                //郵箱驗證信息(賬號與密碼)
                if (this.mb_Authenticate == true)
                {
                    NetworkCredential SMTPUserInfo = new NetworkCredential();
                    SMTPUserInfo.UserName = this.ms_SendUserName;
                    SMTPUserInfo.Password = this.ms_SendPassword;
                    smtp.Credentials = SMTPUserInfo;
                }
                smtp.EnableSsl = bool.Parse(this.ms_SmtpUseSsl);
                smtp.Send(o_mm);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }