jquery ajax 发送邮件例子
<div class="form"> <dl> <dt>您的称呼<small>(必填)</small></dt> <dd><input id="name" type="text" name="name" class="formText" require></dd> </dl> <dl> <dt>您的邮箱<small>(必填)</small></dt> <dd><input id="email" type="text" name="email" class="formText" require></dd> </dl> <dl> <dt>联系电话</dt> <dd><input id="phone" type="text" name="phone" class="formText"></dd> </dl> <dl> <dt>您的想法/意见<small>(必填)</small></dt> <dd><textarea id="message" name="message" class="formText"></textarea></dd> </dl> <div class="formBtn" onclick="btnSend()">发送留言</div> <script> //提交数据 function btnSend() { $("#txtMsg").text(""); var name = $("#name").val();//您的称呼 var email = $("#email").val();//您的邮箱 var phone = $("#phone").val();//联系电话 var message = $("#message").val();//您的想法 if (name.length == 0) { alert("称呼不能为空!"); return; } if (email.length == 0) { alert("邮箱不能为空!"); return; } var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/; if (!myreg.test(email)) { alert('请输入有效的E_mail!'); return; } if (message.length < 20) { alert("意见不能不能少于20个字符!"); return; } $(".formBtn").val("正在发送,请稍等!"); var postData = "name=" + name + "&email=" + email + "&phone=" + phone + "&message=" + message; //向后台发送处理数据 $.ajax({ type: "POST", //用POST方式传输 dataType: "text", //数据格式:JSON url: '/Email.ashx', //目标地址 data: postData, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("发送失败,请联系在线客服!"); }, success: function (msg) { $(".formBtn").val("发送留言"); alert(msg); } }); } </script> </div>
Email.ashx
<%@ WebHandler Language="C#" Class="Email" %> using System; using System.Web; using Ky.Common; public class Email : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string name = KYRequest.GetFormString("name");//您的称呼 string email = KYRequest.GetFormString("email");//您的邮箱 string phone = KYRequest.GetFormString("phone");//联系电话 string message = KYRequest.GetFormString("message");//您的想法 if (string.IsNullOrEmpty(name)) { context.Response.Write("您的称呼为空"); return; } if (string.IsNullOrEmpty(email)) { context.Response.Write("您的邮箱为空"); return; } if (string.IsNullOrEmpty(message)) { context.Response.Write("想法/意见为空"); return; } string body = "时间:" + DateTime.Now + "<br>IP:" + KYRequest.GetIP() + "<br>称呼:" + name + "<br>邮箱:" + email + "<br>电话:" + phone + "<br>想法/意见:" + message; try { string wwwEmail = System.Configuration.ConfigurationManager.AppSettings["wwwEmail"].ToString(); SendMail.Send(wwwEmail, "【邮件助手】您的网站收到留言" + DateTime.Now, body); context.Response.Write("发送成功,感谢您的支持。"); } catch { context.Response.Write("Web.config未设置接收邮箱,发送失败"); } } public bool IsReusable { get { return false; } } }