步步为营-88-邮件发送
以163向qq发送为例
效果如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EmailSend.aspx.cs" Inherits="Web.Test.EmailSendTest.EmailSend" %> <!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:Label ID="lblFrom" runat="server" Text="发件人"></asp:Label> <asp:TextBox ID="txtFrom" runat="server"></asp:TextBox> <asp:Label ID="lblPwd" runat="server" Text="密码(注意密码不是登录密码,而是那个授权码)"></asp:Label> <asp:TextBox ID="txtPwd" TextMode="Password" runat="server"></asp:TextBox> <br /> <asp:Label ID="lblTo" runat="server" Text="收件人"></asp:Label> <asp:TextBox ID="txtTo" runat="server"></asp:TextBox> <br /> <asp:Label ID="lblSubject" runat="server" Text="主题"></asp:Label> <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox> <br /> <asp:Label ID="lblBody" runat="server" Text="内容"></asp:Label> <asp:TextBox ID="txtBody" runat="server"></asp:TextBox> <br /> <asp:Button ID="btnSend" runat="server" Text="发送" OnClick="btnSend_Click" /> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Web.Test.EmailSendTest { public partial class EmailSend : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnSend_Click(object sender, EventArgs e) { System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(); client.Host = "smtp.163.com";//使用163的SMTP服务器发送邮件 client.UseDefaultCredentials = true; client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; client.Credentials = new System.Net.NetworkCredential(this.txtFrom.Text.Trim().ToString(), this.txtPwd.Text.Trim().ToString());//163的SMTP服务器需要用163邮箱的用户名和密码作认证,如果没有需要去163申请个, //这里假定你已经拥有了一个163邮箱的账户,用户名为abc,密码为******* System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage(); Message.From = new System.Net.Mail.MailAddress(this.txtFrom.Text.Trim().ToString());//这里需要注意,163似乎有规定发信人的邮箱地址必须是163的,而且发信人的邮箱用户名必须和上面SMTP服务器认证时的用户名相同 //因为上面用的用户名abc作SMTP服务器认证,所以这里发信人的邮箱地址也应该写为abc@163.com Message.To.Add(this.txtTo.Text.Trim().ToString());//将邮件发送给QQ邮箱 Message.Subject = this.txtSubject.Text.Trim().ToString(); Message.Body = this.txtBody.Text.Trim().ToString(); Message.SubjectEncoding = System.Text.Encoding.UTF8; Message.BodyEncoding = System.Text.Encoding.UTF8; Message.Priority = System.Net.Mail.MailPriority.High; Message.IsBodyHtml = true; client.Send(Message); } } }