Bài viết sau tôi sẽ hướng dẫn các bạn cách gửi mail với app settings trong file Web.Config như thế nào. Đây cũng là cách đơn giản để thực hiện gửi email trong project asp.net
File aspx.cs
Code behind gồm có
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | Mail Message message = new MailMessage (); MailAddress Sender = new MailAddress (ConfigurationManager.AppSettings ["smtpUser"]); MailAddress receiver = new MailAddress (txtemail.Text); SmtpClient smtp = new SmtpClient() { Host = ConfigurationManager.AppSettings ["smtpServer"], Port = Convert.ToInt32 (ConfigurationManager.AppSettings ["smtpPort"]), EnableSsl = true, Credentials = new System.Net.NetworkCredential ( ConfigurationManager.AppSettings ["smtpUser"], ConfigurationManager.AppSettings ["smtpPass"]) }; message.From = Sender; message.To.Add(receiver); message.Body = txtbody.Text; message.IsBodyHtml = true; smtp.Send(message); |
Đoạn code trên sẽ thực hiện gửi mail với code giao diện như sau
1 2 3 4 5 6 | Email ID <asp:TextBox ID="txtemail" runat="server"></asp:TextBox><br /> Subject <asp:TextBox ID="txtsubject" runat="server"></asp:TextBox><br /> Body <asp:TextBox ID="txtbody" runat="server" TextMode="MultiLine"></asp:TextBox><br /> <asp:Button ID="btnSendmail" runat="server" Text="Send" onclick="btnSendmail_Click"/> |
Sau đó bạn vô file Web.config thêm đoạn code sau
1 2 3 4 5 6 7 8 9 10 | <appSettings> <add key="webpages:Version" value="1.0.0.0" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> <add key="smtpServer" value="smtp.gmail.com" /> <add key="EnableSsl" value = "true"/> <add key="smtpPort" value="587" /> <add key="smtpUser" value="abc@gmail.com" /> <add key="smtpPass" value="*****" /> </appSettings> |
Nếu như có thẻ appSettings rồi thì bạn chỉ việc thêm các key trên vào là được.
Ưu điểm của phương pháp
Ưu điểm lớn nhất phải kể đến đó là chúng ta không phải viết lại các đoạn mã gửi mail nữa, việc config trực tiếp trong file Web.Config sẽ khiến cho mỗi lần chúng ta phải sửa các thông số gửi mail sẽ không còn vất vả nữa. Do đó sẽ làm giảm sự cồng kềnh của code, giúp cho code sáng sủa và minh bạch hơn rất nhiều.
You must log in to post a comment.