都會使用寄信通知功能。
那當然若能將那些信件內容拉出來,
可以在外編輯,而不需動到程式該有多好,
下面這些程式因此產生。
我採用的是中間有一層gmail帳號,
透過此信箱傳送至那些使用者信箱去。
因此首先必須設定此gmail帳號資訊,
程式碼如下(須貼至Web.Config檔中):
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="sample@gmail.com">
<network host="smtp.gmail.com" userName="sample" password="sample"/>
</smtp>
</mailSettings>
</system.net>
上面的"from"、"host"、"userName"、"password"變數
換成自己家的,
到這寄信帳號設定已完成。
接下來是準備mailBody的部分,
要準備一個htm文件,
當然要以html格式去編寫它,
變數需要用特殊符號前後包起來,
這樣才可以再組信件內容時
可以依照不同使用者填入個別的資訊。
範例如下:
<html>
<body>
<h2>恭喜您註冊成功!</h2>
<p>
此電子郵件確認您的帳號及密碼。
</p>
<p>
要登錄到該網站,請使用下列憑證:
</p>
<table>
<tr>
<td>
<b>帳號:</b>
</td>
<td>
<%UserName%>
</td>
</tr>
<tr>
<td>
<b>密碼:</b>
</td>
<td>
<%Password%>
</td>
</tr>
</table>
<p>
如果您有任何疑問,或在登錄時遇到任何問題,請聯繫網管人員。
</p>
</body>
</html>
上面變數使用<%%>包起來,
到時可以動態換上資訊。
//寄mail部分
StreamReader reader = new StreamReader(Server.MapPath("~/MailSample/CreateAccountMail.htm"),System.Text.Encoding.GetEncoding("big5"));
string readFile = reader.ReadToEnd();
string MailBody = readFile;
MailBody = MailBody.Replace("<%UserName%>", txtEMail.Text);
MailBody = MailBody.Replace("<%Password%>", txtPass.Text);
Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
MailSettingsSectionGroup settings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient(settings.Smtp.Network.Host);//"smtp.gmail.com"
mail.From = new MailAddress(settings.Smtp.From);
mail.To.Add(txtEMail.Text);
mail.Subject = "恭喜您註冊成功!";
mail.Body = MailBody;
mail.IsBodyHtml = true;
SmtpServer.Port = 587;
SmtpServer.EnableSsl = true;
SmtpServer.Credentials = new System.Net.NetworkCredential(settings.Smtp.Network.UserName, settings.Smtp.Network.Password);
SmtpServer.Send(mail);
上面程式碼需要講解一下,
我把所有的htm檔案都放在MailSample資料夾中,
所以我在讀取htm檔時設定讀取路徑:~/MailSample/CreateAccountMail.htm,
當然htm檔案文字中有中文字時記得使用big5解碼。
讀到的檔案用MailBody變數接起來,
再用replace將變數換掉即可。
接下來寄信帳號資訊擷取,
使用MailSettingsSectionGroup。
記得信件內容設定為html格式,
"mail.IsBodyHtml = true;"
才會使得htm檔中的html語法才會有效果。
照著這幾個步驟設定,
就可以完成寄信的功能了,
當然你可以設定不同的htm檔案,
去完成不同作業。
最近學到的一招,
放在網路上以備不時之需。
下回見!!!