本文分享一个C#利用SMTP发送邮件的案例,提供了前后台代码,方便大家学习。
1.前端HTML使用了Jquery,大家如果做演示不要忘记引入Jquery的库
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.easck.com/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.easck.com/1999/xhtml">
<head>
<title></title>
<script src="jquery-1.8.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
function sendemail() {
var smtp = $('#txtSmtp').val();
var content = $('#txtContent').val();
var var from = $('#txtFrom').val();
var to = $('#txtTo').val();
$.post("Handler.ashx", { 'smtp': smtp, 'content': content,'title':title, 'from': from, 'to': to },
function (data) {
var n = eval('(' + data + ')');
if (n.success) {
alert(n.message);
}
});
}
</script>
</head>
<body>
<table>
<tr><td>smtp:</td>
<td><input type="text" id = "txtSmtp" value="Smtp Server" />
</td>
</tr>
<tr><td>from addr:</td>
<td><input type="text" id = "txtFrom" value="xxx@xxx.com" />
</td>
</tr>
<tr><td>to addr:</td>
<td><input type="text" id = "txtTo" value="xxx@xxx.com" />
</td>
</tr>
<tr><td>title:</td>
<td><input type="text" id = "txtTitle" value="title" />
</td>
</tr>
<tr><td>content:</td>
<td><input type="text" id = "txtContent" value="Content" />
</td>
</tr>
<tr>
<td>
<input type="button" id="btnSend" value="send" onclick="sendemail()"/>
</td>
</tr>
</table>
</body>
</html>
2.后台代码是一般处理类 ashx,供前台异步调用
<%@ WebHandler Language="C#" class="Handler" %>
using System;
using System.Web;
using Utility;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/plain";
string smtp = HttpContext.Current.Request.Form["smtp"].ToString();
string string content = HttpContext.Current.Request.Form["content"].ToString();
string from = HttpContext.Current.Request.Form["from"].ToString();
string to = HttpContext.Current.Request.Form["to"].ToString();
try
{
EmailClient emailClient = new EmailClient(smtp);// localhost::25
emailClient.SendEmail(from, to, title, content);
System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
System.Collections.Generic.Dictionary<string, object> d = new System.Collections.Generic.Dictionary<string, object>();
d.Add("message", "success");
d.Add("success", true);
context.Response.Write(jss.Serialize(d));
}
catch (Exception ex)
{
System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
System.Collections.Generic.Dictionary<string, object> d = new System.Collections.Generic.Dictionary<string, object>();
d.Add("message", ex.Message);
d.Add("success", true);
context.Response.Write(jss.Serialize(d));
}
}
public bool IsReusable {
get {
return false;
}
}
}










