asp.net簡單發送郵件代碼

 protected void SendMailLocalhost(string ToMail, string Name, string Pwd)
    {
        System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
        msg.To.Add(ToMail); //收郵件地址
       
        //msg.CC.Add("[email protected]");可以抄送給多人
      
        msg.From = new System.Net.Mail.MailAddress("[email protected]", "admin", System.Text.Encoding.UTF8);
        /* 上面3個參數分別是發件人地址(可以隨便寫),發件人姓名,編碼*/

        msg.Subject = "發給您的用戶名和密碼";//郵件標題
        msg.SubjectEncoding = System.Text.Encoding.UTF8;//郵件標題編碼
        msg.Body = "您的用戶名是:" + Name + ",密碼是:" + Pwd; //郵件內容
        msg.BodyEncoding = System.Text.Encoding.UTF8;//郵件內容編碼
        msg.IsBodyHtml = false;//是否是HTML郵件
        msg.Priority = System.Net.Mail.MailPriority.High;//郵件優先級

 

        //System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
        //client.Host = "localhost";

 

        //System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
        //client.Credentials = new System.Net.NetworkCredential("[email protected]", "xxx");
        //註冊的郵箱和密碼
        //client.Host = "smtp.yahoo.com.cn";

 

        System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
        client.Credentials = new System.Net.NetworkCredential("[email protected]", "xxx");
        //上述寫你的GMail郵箱和密碼
        client.Port = 587;//Gmail使用的端口
        client.Host = "smtp.gmail.com";
        client.EnableSsl = true;//經過ssl加密


        object userState = msg;
        try
        {
            //client.SendAsync(msg, userState); //此爲異步傳輸
            client.Send(msg);
            this.lblMsgMail.Visible = true;
            this.lblMsgMail.Text = "郵件發送成功!";
            this.lblMsgMail.ForeColor = System.Drawing.Color.Red;
        }
        catch (System.Net.Mail.SmtpException ex)
        {
            //ex = null;
            this.lblMsgMail.Visible = true;
            this.lblMsgMail.Text = "發送郵件出錯!" + ex.ToString();
            this.lblMsgMail.ForeColor = System.Drawing.Color.Red;
        }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章