前端代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <form id="form1" runat="server"> <div> 收件人:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /> 标题:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br /> 正文:<asp:TextBox ID="TextBox3" TextMode="MultiLine" runat="server"></asp:TextBox> <br /> <asp:Button ID="Button1" runat="server" Text="发送" /> </div> </form> </body> </html>
右键查看代码
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net;//引用命名空间 using System.Net.Mail;//引用命名空间 public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Button1.Click += Button1_Click; } //发送邮箱的点击事件 void Button1_Click(object sender, EventArgs e) { //建立一个服务器类 需要邮箱服务器(需要开启邮箱的各种服务)smtp.qq.com应该是IP经过特殊处理和IP一样的作用 SmtpClient smtp = new SmtpClient("smtp.sina.com"); //发件人 MailAddress from = new MailAddress("***********@sina.cn"); //收件人 MailAddress to = new MailAddress(TextBox1.Text); //邮件整体(发件人地址(from),收件人地址(to)) MailMessage msg = new MailMessage(from, to); //邮件标题 msg.Subject = TextBox2.Text; //邮件内容 msg.Body = TextBox3.Text; smtp.UseDefaultCredentials = false; //证书类用于做互联网证书用的(发件人的用户名和密码)qq等的密码会用掩码代替 NetworkCredential cred = new NetworkCredential("**********@sina.cn", "********"); //需要证书一起发过去(就是发件人的用户名和密码) smtp.Credentials = cred; //通过建立的邮箱服务器(smtp)准备发给服务器(msg) smtp.Send(msg); } }
效果
发送前
发送后