Friday, March 13, 2015

Cấu hình gmail và sử dụng c# để gửi thư trong asp.net

Một trong các chức năng phổ biến hiện nay là liên lạc với người dung qua thư điện tử. Trong asp.net là công nghệ phát triển web rât mạnh nên họ cũng hỗ trợ gởi thử một cách rất đơn giản qua thư viện SmtpClient.

Trong hướng dẫn này chúng ta cùng cấu hình mail server (sử dụng mail miễn phí Gmail) trên website asp.net.

Bước 1: Cấu hình mail server qua web.config. Bổ sung mã nguồn sau và giữa thẻ configuration

[sourcecode language="xml"]
<system.net>
<mailSettings>
<smtp from="ngotuongdan@gmail.com">
<network host="smtp.gmail.com" password="mật khẩu" port="587"
userName="tài khoản" />
</smtp>
</mailSettings>
</system.net>
[/sourcecode]

Bước 2: Sử dụng thư viện smtp để gởi thư


[sourcecode language="csharp"]
public Mailer(string Email, string MatKhau, string TaiKhoan)
{
try
{
var smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
string strHost = smtpSection.Network.Host;
int port = smtpSection.Network.Port;
string strUserName = smtpSection.Network.UserName;
string strFromPass = smtpSection.Network.Password;
SmtpClient smtp = new SmtpClient(strHost, port);
NetworkCredential cert = new NetworkCredential(strUserName, strFromPass);
smtp.Credentials = cert;
smtp.EnableSsl = true;
MailMessage msg = new MailMessage(smtpSection.From, Email);
msg.Subject = "Thông tin đăng ký !";
msg.IsBodyHtml = true;
msg.Body += "<h1>Trung tâm quản lý người dùng.</h1>";
msg.Body += "<h3> http://" + WebConfigurationManager.AppSettings["domain"].ToString() + "</h3>";
msg.Body += "Bạn vừa đăng ký sử dụng hệ thống web GIS.<br/>";
msg.Body += "<br/>Tên đăng nhập của bạn là: <b>" + TaiKhoan + "</b>";
msg.Body += "<br/><br/>Mật khẩu của bạn là: <b>" + MatKhau + "</b><br/>";
msg.Body += "<hr/>Bạn nên đổi mật khẩu.";
smtp.Send(msg);
HttpContext.Current.Response.Write("<script>alert('Gởi thư thành công.');</script>");
}catch(Exception ex)
{
HttpContext.Current.Response.Write("<script>alert('Không gởi mail được');</script>");
}
}
[/sourcecode]

Như vậy là chúng ta có thể gởi được một email tới địa chỉ của người nhận.

No comments:

Post a Comment

Translate