参考:
*http://blog.csdn.net/bbch3/archive/2006/12/08/1434232.aspx
*http://groups.google.com/group/microsoft.public.dotnet.framework.aspnet/browse_frm/thread/f2ef95e6fb1e0112/17e4601e26e355ba?hl=en&lr=&ie=UTF-8&oe=UTF8&newwindow=1&rnum=75&prev=/groups%3Fq%3Dcdo.message%2Bgroup:microsoft.public.dotnet.*%26num%3D50%26hl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF8%26newwindow%253#17e4601e26e355ba
*http://blog.joycode.com/ghj/archive/2004/10/22/36274.aspx
在项目里新建一个email.aspx页面。在email里拖入三个文本框,分别命名为:tbTo、tbSubject、tbBody,它们分别是用做:收件人、Email的主题、Email的内容。然后再加入一个按钮。
双击按钮,在email.aspx.cs页面里,添加“using System.Web.Mail;”的引用。
再在
Page_Load
事件里加入以下代码:
if (!this.IsPostBack)
{}
if (!this.IsPostBack)
{}
然后在
Button1_Click
事件里加入以下代码:
MailMessage myMail = new MailMessage();
myMail.Subject = this.tbSubject.Text.Trim();
myMail.From = smallfools@hotmail.com;
myMail.To = this.tbTo.Text.Trim();
myMail.Body = this.tbBody.Text;
SmtpMail.SmtpServer = "smtp 服务器的地址 ";
SmtpMail.Send(myMail);
Response.Write(" 发送成功 ");
MailMessage myMail = new MailMessage();
myMail.Subject = this.tbSubject.Text.Trim();
myMail.From = smallfools@hotmail.com;
myMail.To = this.tbTo.Text.Trim();
myMail.Body = this.tbBody.Text;
SmtpMail.SmtpServer = "smtp 服务器的地址 ";
SmtpMail.Send(myMail);
Response.Write(" 发送成功 ");
只要把
SmtpMail.SmtpServer
换成您的
smtp
服务器名或
IP
就可以了。编译看看运行结果吧。
完整的代码如下:
email.aspx
:
<%@ Page language="c#" Codebehind="email.aspx.cs" AutoEventWireup="false" Inherits="test.email" %>
<!
DOCTYPE
HTML
PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"
>
<
HTML
>
<HEAD>
<title>email</title>
<metaname="GENERATOR"Content="Microsoft Visual Studio .NET 7.1">
<metaname="CODE_LANGUAGE"Content="C#">
<metaname="vs_defaultClientScript"content="JavaScript">
<metaname="vs_targetSchema"content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<formid="Form1"method="post"runat="server">
<P>
<FONTface="宋体">收件人:
<asp:TextBoxid="tbTo"runat="server"Width="232px"></asp:TextBox></FONT></P>
<P><FONTface="宋体">主题:
<asp:TextBoxid="tbSubject"runat="server"Width="248px"></asp:TextBox></FONT></P>
<P><FONTface="宋体">内容:
<asp:TextBoxid="tbBody"runat="server"TextMode="MultiLine"Width="256px"Height="128px"></asp:TextBox></FONT></P>
<P><FONTface="宋体">
<asp:Buttonid="Button1"runat="server"Text="发送"></asp:Button></P>
</FONT>
</form>
</body>
</
HTML
>
email.aspx.cs
:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Mail;
namespace test
{
///<summary>
/// email 的摘要说明。
///</summary>
public class email : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.TextBox tbSubject;
protected System.Web.UI.WebControls.TextBox tbBody;
protected System.Web.UI.WebControls.TextBox tbTo;
private void Page_Load(object sender, System.EventArgs e)
{
if (!this.IsPostBack)
{
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
///<summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
///</summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Button1_Click(object sender, System.EventArgs e)
{
MailMessage myMail = new MailMessage();
myMail.Subject = this.tbSubject.Text.Trim();
myMail.From = "smallfools@hotmail.com";
myMail.To = this.tbTo.Text.Trim();
myMail.Body = this.tbBody.Text;
SmtpMail.SmtpServer = "smtp服务器的地址";
SmtpMail.Send(myMail);
Response.Write("OK");
}
}
}
上章里说到,在asp.net里怎么发送邮件。主要是用到System.Web.Mail类。但是现在很多stmp服务器,都需要身份验证,如果不通过身份验证的话,它是不会让你发送邮件的。
为此.net的MailMessage类里提供了Fields属性,可以附加身份的验证代码。
只要在上章的Button1_Click事件里加上以下代码,即可通过身份验证了:
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1用户名");
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/sendpassword密码"); ", ");
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/sendusername", "
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1用户名");
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/sendpassword密码"); ", ");
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/sendusername", "
编译后看看效果吧,完整代码如下:
email.aspx:
<%@ Page language="c#" Codebehind="email.aspx.cs" AutoEventWireup="false" Inherits="test.email" %>
<!
DOCTYPE
HTML
PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"
>
<
HTML
>
<HEAD>
<title>email</title>
<metaname="GENERATOR"Content="Microsoft Visual Studio .NET 7.1">
<metaname="CODE_LANGUAGE"Content="C#">
<metaname="vs_defaultClientScript"content="JavaScript">
<metaname="vs_targetSchema"content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<formid="Form1"method="post"runat="server">
<P>
<FONTface="宋体">收件人:
<asp:TextBoxid="tbTo"runat="server"Width="232px"></asp:TextBox></FONT></P>
<P><FONTface="宋体">主题:
<asp:TextBoxid="tbSubject"runat="server"Width="248px"></asp:TextBox></FONT></P>
<P><FONTface="宋体">内容:
<asp:TextBoxid="tbBody"runat="server"TextMode="MultiLine"Width="256px"Height="128px"></asp:TextBox></FONT></P>
<P><FONTface="宋体">
<asp:Buttonid="Button1"runat="server"Text="发送"></asp:Button></P>
</FONT>
</form>
</body>
</
HTML
>
email.aspx.cs
:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Mail;
namespace test
{
///<summary>
/// email 的摘要说明。
///</summary>
public class email : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.TextBox tbSubject;
protected System.Web.UI.WebControls.TextBox tbBody;
protected System.Web.UI.WebControls.TextBox tbTo;
private void Page_Load(object sender, System.EventArgs e)
{
if (!this.IsPostBack)
{
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
///<summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
///</summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Button1_Click(object sender, System.EventArgs e)
{
MailMessage myMail = new MailMessage();
myMail.Subject = this.tbSubject.Text.Trim();
myMail.From = "smallfools@sina.com";
myMail.To = this.tbTo.Text.Trim();
myMail.Body = this.tbBody.Text;
SmtpMail.SmtpServer = "smtp.sina.com.cn";
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1);
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "用户名");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "密码");
SmtpMail.Send(myMail);
Response.Write("OK");
}
}
}
跟据前面所说,我们已经可以用asp.net发送email了,但是发送email里有一个重要的功能:发送附件,我们还没有实现,下面我们来看看要怎么样在email里发送一个附件。
还是在email.aspx文件里,拖入一个File Field的HTML组件。然后在HTML里把“<INPUT type="file">”改为“<INPUT type="file" runat="server" id="upfile">”。
然后回到email.aspx.cs页面,增加一个“using System.IO;”引用。
再在Button1_Click事件里,把内容改为以下代码:
MailMessage myMail = new MailMessage();
myMail.Subject = this.tbSubject.Text.Trim();
myMail.From = " smallfools@sina.com";
myMail.To = this.tbTo.Text.Trim();
myMail.Body = this.tbBody.Text;
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1);
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/sendusername", "smallfools");
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/sendpassword", "*******");
MailMessage myMail = new MailMessage();
myMail.Subject = this.tbSubject.Text.Trim();
myMail.From = " smallfools@sina.com";
myMail.To = this.tbTo.Text.Trim();
myMail.Body = this.tbBody.Text;
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1);
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/sendusername", "smallfools");
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/sendpassword", "*******");
string ServerFileName = "";
if (this.upfile.PostedFile.ContentLength != 0)
{
string upFileName = this.upfile.PostedFile.FileName;
string[] strTemp = upFileName.Split('.');
string upFileExp = strTemp[strTemp.Length-1].ToString();
ServerFileName = Server.MapPath(DateTime.Now.ToString("yyyyMMddhhmmss")+"."+upFileExp);
this.upfile.PostedFile.SaveAs(ServerFileName);
MailAttachment myAttachment = new System.Web.Mail.MailAttachment(ServerFileName);
myMail.Attachments.Add(myAttachment);
}
{
string upFileName = this.upfile.PostedFile.FileName;
string[] strTemp = upFileName.Split('.');
string upFileExp = strTemp[strTemp.Length-1].ToString();
ServerFileName = Server.MapPath(DateTime.Now.ToString("yyyyMMddhhmmss")+"."+upFileExp);
this.upfile.PostedFile.SaveAs(ServerFileName);
MailAttachment myAttachment = new System.Web.Mail.MailAttachment(ServerFileName);
myMail.Attachments.Add(myAttachment);
}
SmtpMail.SmtpServer = "smtp.sina.com.cn";
SmtpMail.Send(myMail);
SmtpMail.Send(myMail);
if (ServerFileName!="")
{
FileInfo myFile = new FileInfo(ServerFileName);
myFile.Delete();
}
{
FileInfo myFile = new FileInfo(ServerFileName);
myFile.Delete();
}
Page.RegisterClientScriptBlock("ok","<script language=javascript>alert('发送成功')</script>");
这样,我们就可以上传一个附件。完整代码如下:
email.aspx:
<%@ Page language="c#" Codebehind="email.aspx.cs" AutoEventWireup="false" Inherits="test.email" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>email</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<P>
<FONT">宋体">收件人:
<asp:TextBox id="tbTo" runat="server" Width="232px"></asp:TextBox></FONT></P>
<P><FONT">宋体">主题:
<asp:TextBox id="tbSubject" runat="server" Width="248px"></asp:TextBox></FONT></P>
<P><FONT">宋体">内容:
<asp:TextBox id="tbBody" runat="server" TextMode="MultiLine" Width="256px" Height="128px"></asp:TextBox></FONT></P>
<P><FONT">宋体">附件:<INPUT type="file" runat="server" id="upfile"></P>
</FONT>
<P><FONT">宋体">
<asp:Button id="Button1" runat="server" Text="发送"></asp:Button></P>
</FONT>
</form>
</body>
</HTML>
email.aspx.cs:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Mail;
using System.IO;
namespace test
{
/// <summary>
/// email 的摘要说明。
/// </summary>
public class email : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.TextBox tbSubject;
protected System.Web.UI.WebControls.TextBox tbBody;
protected System.Web.UI.HtmlControls.HtmlInputFile upfile;
protected System.Web.UI.WebControls.TextBox tbTo;
private void Page_Load(object sender, System.EventArgs e)
{
if (!this.IsPostBack)
{
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Button1_Click(object sender, System.EventArgs e)
{
MailMessage myMail = new MailMessage();
myMail.Subject = this.tbSubject.Text.Trim();
myMail.From = "smallfools@sina.com";
myMail.To = this.tbTo.Text.Trim();
myMail.Body = this.tbBody.Text;
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1);
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", " smallfools");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "******");
string ServerFileName = "";
if (this.upfile.PostedFile.ContentLength != 0)
{
string upFileName = this.upfile.PostedFile.FileName;
string[] strTemp = upFileName.Split('.');
string upFileExp = strTemp[strTemp.Length-1].ToString();
ServerFileName = Server.MapPath(DateTime.Now.ToString("yyyyMMddhhmmss")+"."+upFileExp);
this.upfile.PostedFile.SaveAs(ServerFileName);
MailAttachment myAttachment = new System.Web.Mail.MailAttachment(ServerFileName);
myMail.Attachments.Add(myAttachment);
}
SmtpMail.SmtpServer = "smtp.sina.com.cn";
SmtpMail.Send(myMail);
if (ServerFileName!="")
{
FileInfo myFile = new FileInfo(ServerFileName);
myFile.Delete();
}
Page.RegisterClientScriptBlock("ok","<script language=javascript>alert('发送成功')</script>");
}
}
}
在上章里,我们已经知道要怎么发送一个附件了,但是如果要发送多个附件的话,还要对网页再进行一点点修改。
打开email.asp页面,加入两个按钮,以及一个DropDownList控件。如下图所示。
双击“上传”按钮,在Button2_Click事件里添加以下代码:
if (this.upfile.PostedFile.ContentLength != 0)
{
string clientFileName = this.upfile.PostedFile.FileName;
string[] strTemp = clientFileName.Split('.');
string upFileExp = strTemp[strTemp.Length-1].ToString();
string ServerFileName = DateTime.Now.ToString("yyyyMMddhhmmss")+"."+upFileExp;
this.upfile.PostedFile.SaveAs(Server.MapPath(ServerFileName));
this.DropDownList1.Items.Add(new ListItem(clientFileName,ServerFileName));
if (this.upfile.PostedFile.ContentLength != 0)
{
string clientFileName = this.upfile.PostedFile.FileName;
string[] strTemp = clientFileName.Split('.');
string upFileExp = strTemp[strTemp.Length-1].ToString();
string ServerFileName = DateTime.Now.ToString("yyyyMMddhhmmss")+"."+upFileExp;
this.upfile.PostedFile.SaveAs(Server.MapPath(ServerFileName));
this.DropDownList1.Items.Add(new ListItem(clientFileName,ServerFileName));
if (this.DropDownList1.Items.Count>0)
{
this.Button3.Enabled = true;
}
else
{
this.Button3.Enabled = false;
}
}
{
this.Button3.Enabled = true;
}
else
{
this.Button3.Enabled = false;
}
}
双击“删除”按钮,在Button3_Click事件里添加以下代码:
FileInfo myFile = new FileInfo(Server.MapPath(this.DropDownList1.SelectedValue));
myFile.Delete();
FileInfo myFile = new FileInfo(Server.MapPath(this.DropDownList1.SelectedValue));
myFile.Delete();
this.DropDownList1.Items.Remove(this.DropDownList1.Items[this.DropDownList1.SelectedIndex]);
if (this.DropDownList1.Items.Count>0)
{
this.Button3.Enabled = true;
}
else
{
this.Button3.Enabled = false;
}
{
this.Button3.Enabled = true;
}
else
{
this.Button3.Enabled = false;
}
再把Button1_Click事件里的代码改成:
MailMessage myMail = new MailMessage();
myMail.Subject = this.tbSubject.Text.Trim();
myMail.From = " smallfools@sina.com";
myMail.To = this.tbTo.Text.Trim();
myMail.Body = this.tbBody.Text;
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1);
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/sendusername", "smallfools");
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/sendpassword", "****");
MailMessage myMail = new MailMessage();
myMail.Subject = this.tbSubject.Text.Trim();
myMail.From = " smallfools@sina.com";
myMail.To = this.tbTo.Text.Trim();
myMail.Body = this.tbBody.Text;
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1);
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/sendusername", "smallfools");
myMail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/sendpassword", "****");
if (this.DropDownList1.Items.Count>0)
{
for (int i=0;i<this.DropDownList1.Items.Count;i++)
{
MailAttachment myAttachment = new System.Web.Mail.MailAttachment(Server.MapPath(this.DropDownList1.Items[i].Value));
myMail.Attachments.Add(myAttachment);
}
{
for (int i=0;i<this.DropDownList1.Items.Count;i++)
{
MailAttachment myAttachment = new System.Web.Mail.MailAttachment(Server.MapPath(this.DropDownList1.Items[i].Value));
myMail.Attachments.Add(myAttachment);
}
}
SmtpMail.SmtpServer = "smtp.sina.com.cn";
SmtpMail.Send(myMail);
SmtpMail.Send(myMail);
if (this.DropDownList1.Items.Count>0)
{
for (int i=0;i<this.DropDownList1.Items.Count;i++)
{
FileInfo myFile = new FileInfo(Server.MapPath(this.DropDownList1.Items[i].Value));
myFile.Delete();
}
}
{
for (int i=0;i<this.DropDownList1.Items.Count;i++)
{
FileInfo myFile = new FileInfo(Server.MapPath(this.DropDownList1.Items[i].Value));
myFile.Delete();
}
}
Page.RegisterClientScriptBlock("ok","<script language=javascript>alert('发送成功')</script>");
编译后运行即可。完整的代码如下:
Email.aspx:
<%@ Page language="c#" Codebehind="email.aspx.cs" AutoEventWireup="false" Inherits="test.email" %>
<%@ Page language="c#" Codebehind="email.aspx.cs" AutoEventWireup="false" Inherits="test.email" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>email</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<P><FONT">宋体">收件人:
<asp:textbox id="tbTo" runat="server" Width="232px"></asp:textbox></FONT></P>
<P><FONT">宋体">主题:
<asp:textbox id="tbSubject" runat="server" Width="248px"></asp:textbox></FONT></P>
<P><FONT">宋体">内容:
<asp:textbox id="tbBody" runat="server" Width="256px" Height="128px" TextMode="MultiLine"></asp:textbox></FONT></P>
<P><FONT">宋体">附件:<INPUT id="upfile" type="file" runat="server">
<asp:Button id="Button2" runat="server" Text="上传"></asp:Button></FONT></P>
<P><FONT">宋体">已上传附件:
<asp:DropDownList id="DropDownList1" runat="server"></asp:DropDownList>
<asp:Button id="Button3" runat="server" Text="删除" Enabled="False"></asp:Button></P>
</FONT>
<P><FONT">宋体"><asp:button id="Button1" runat="server" Text="发送"></asp:button></P>
</FONT></form>
</body>
</HTML>
Email.aspx.cs:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Mail;
using System.IO;
namespace test
{
/// <summary>
/// email 的摘要说明。
/// </summary>
public class email : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.TextBox tbSubject;
protected System.Web.UI.WebControls.TextBox tbBody;
protected System.Web.UI.HtmlControls.HtmlInputFile upfile;
protected System.Web.UI.WebControls.DropDownList DropDownList1;
protected System.Web.UI.WebControls.Button Button2;
protected System.Web.UI.WebControls.Button Button3;
protected System.Web.UI.WebControls.TextBox tbTo;
private void Page_Load(object sender, System.EventArgs e)
{
if (!this.IsPostBack)
{
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Button2.Click += new System.EventHandler(this.Button2_Click);
this.Button3.Click += new System.EventHandler(this.Button3_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Button1_Click(object sender, System.EventArgs e)
{
MailMessage myMail = new MailMessage();
myMail.Subject = this.tbSubject.Text.Trim();
myMail.From = "smallfools@sina.com";
myMail.To = this.tbTo.Text.Trim();
myMail.Body = this.tbBody.Text;
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1);
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", " smallfools");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "****");
if (this.DropDownList1.Items.Count>0)
{
for (int i=0;i<this.DropDownList1.Items.Count;i++)
{
MailAttachment myAttachment = new System.Web.Mail.MailAttachment(Server.MapPath(this.DropDownList1.Items[i].Value));
myMail.Attachments.Add(myAttachment);
}
}
SmtpMail.SmtpServer = "smtp.sina.com.cn";
SmtpMail.Send(myMail);
if (this.DropDownList1.Items.Count>0)
{
for (int i=0;i<this.DropDownList1.Items.Count;i++)
{
FileInfo myFile = new FileInfo(Server.MapPath(this.DropDownList1.Items[i].Value));
myFile.Delete();
}
}
Page.RegisterClientScriptBlock("ok","<script language=javascript>alert('发送成功')</script>");
}
private void Button2_Click(object sender, System.EventArgs e)
{
if (this.upfile.PostedFile.ContentLength != 0)
{
string clientFileName = this.upfile.PostedFile.FileName;
string[] strTemp = clientFileName.Split('.');
string upFileExp = strTemp[strTemp.Length-1].ToString();
string ServerFileName = DateTime.Now.ToString("yyyyMMddhhmmss")+"."+upFileExp;
this.upfile.PostedFile.SaveAs(Server.MapPath(ServerFileName));
this.DropDownList1.Items.Add(new ListItem(clientFileName,ServerFileName));
if (this.DropDownList1.Items.Count>0)
{
this.Button3.Enabled = true;
}
else
{
this.Button3.Enabled = false;
}
}
}
private void Button3_Click(object sender, System.EventArgs e)
{
FileInfo myFile = new FileInfo(Server.MapPath(this.DropDownList1.SelectedValue));
myFile.Delete();
this.DropDownList1.Items.Remove(this.DropDownList1.Items[this.DropDownList1.SelectedIndex]);
if (this.DropDownList1.Items.Count>0)
{
this.Button3.Enabled = true;
}
else
{
this.Button3.Enabled = false;
}
}
}
}
跟据前面几章的基础,我们现在可以把发送Email的类提炼出来了,以后可以直接使用。
为了使用方便,先建立一个smallfoolsEmail.xml,把一般设置都放在里面,这样的话,程序编好后,如果要修改smtp服务器的设置,只要把smallfoolsEmail.xml文件改改就行,不用重新编译了。
smallfoolsEmail.xml的内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<email>
<emailset>
<!-- smtp服务器的地址 -->
<SmtpAddress>smtp.sina.com.cn</SmtpAddress>
<!-- 邮件回复到哪个信箱里 -->
<ReplyTo>smallfools@hotmail.com</ReplyTo>
<!-- smtp服务器是否需要验证(需要为true,不需要为false) -->
<validate>true</validate>
<!-- 如果smtp服务器要验证的话,验证的用户名 -->
<SendUserName>smallfools</SendUserName>
<!-- 如果smtp服务器要验证的话,验证的密码 -->
<SendPassword>smallfools</SendPassword>
</emailset>
</email>
再建一个smallfoolsEmail.cs文件,把发送邮件所要的操作都放在里面。内容如下:
using System;
using System.Text;
using System.Xml;
using System.IO;
using System.Web.Mail;
namespace email
{
/// <summary>
/// 小笨笨的发送邮件类
/// </summary>
public class smallfoolsEmail
{/// <summary>
/// smtp服务器地址
/// </summary>
public string SmtpAddress = "";
/// <summary>
/// smtp服务器是否需要验证(需要为true,不需要为false)
/// </summary>
public bool validate = false;
/// <summary>
/// 如果smtp服务器要验证的话,验证的用户名
/// </summary>
public string SendUserName = "";
/// <summary>
/// 如果smtp服务器要验证的话,验证的密码
/// </summary>
public string SendPassword = "";
/// <summary>
/// 邮件回复到哪个信箱里
/// </summary>
public string ReplyTo = "";
/// <summary>
/// 初始化smallfoolsEmail类
/// </summary>
public smallfoolsEmail()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(System.Web.HttpContext.Current.Server.MapPath("smallfoolsEmail.xml"));
XmlNode myNode = xmlDoc.DocumentElement.FirstChild;
if (myNode!=null)
{
SmtpAddress = myNode["SmtpAddress"].InnerText;
validate = bool.Parse(myNode["validate"].InnerText);
SendUserName = myNode["SendUserName"].InnerText;
SendPassword = myNode["SendPassword"].InnerText;
ReplyTo = myNode["ReplyTo"].InnerText;
}
}
/// <summary>
/// 发送Email
/// </summary>
/// <param name="To">收件人email地址,可用用“;”分开的多个地址</param>
/// <param name="Cc">抄送地址</param>
/// <param name="Bcc">暗送地址</param>
/// <param name="Subject">邮件主题</param>
/// <param name="Body">邮件正文</param>
/// <param name="Priority">优先级</param>
/// <param name="IsHtml">是否HTML邮件</param>
/// <param name="Attachments">附件列表</param>
public bool SendEmail(string To,string Cc,string Bcc,string Subject,string Body,string Priority,bool IsHtml,string[] Attachments)
{
bool bFlag = false;
if (!IsHtml)
{
Body = System.Web.HttpContext.Current.Server.HtmlDecode(Body);
}
MailMessage myMail = new MailMessage();
myMail.To = To;
myMail.From = ReplyTo;
myMail.Cc = Cc;
myMail.Bcc = Bcc;
myMail.Subject = Subject;
myMail.Body = Body;
myMail.Priority = mailPriority(Priority);
for (int i=0;i<Attachments.Length;i++)
{
MailAttachment myAttachment = new System.Web.Mail.MailAttachment(Attachments[i].ToString());
myMail.Attachments.Add(myAttachment);
}
SmtpMail.SmtpServer = SmtpAddress;
if (validate)
{
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1);
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", SendUserName);
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", SendPassword);
}
try
{
SmtpMail.Send(myMail);
bFlag = true;
}
catch(Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.Message);
}
if (bFlag)
{
for (int i=0;i<Attachments.Length;i++)
{
DelFile(Attachments[i].ToString());
}
}
return bFlag;
}
/// <summary>
/// 返回邮件发送优先级
/// </summary>
private System.Web.Mail.MailPriority mailPriority(string Priority)
{
Priority = Priority.ToLower();
MailPriority rePriority = MailPriority.Normal;
switch (Priority)
{
case "high" :
rePriority = MailPriority.High;
break;
case "low" :
rePriority = MailPriority.Low;
break;
case "normal" :
rePriority = MailPriority.Normal;
break;
}
return rePriority;
}
/// <summary>
/// 上传附件
/// </summary>
/// <param name="PostedFile">客户端文件</param>
public bool UpFile(System.Web.HttpPostedFile PostedFile)
{
bool bFlag = false;
string clientFileName = PostedFile.FileName;
string[] strTemp = clientFileName.Split('//');
string ServerFileName = System.Web.HttpContext.Current.Server.MapPath("Attachments//"+strTemp[strTemp.Length-1].ToString());
try
{
PostedFile.SaveAs(ServerFileName);
bFlag = true;
}
catch
{}
return bFlag;
}
/// <summary>
/// 删除上传附件
/// </summary>
/// <param name="PostedFile">服务器端附件名</param>
public bool DelFile(string ServerFileName)
{
bool bFlag = false;
try
{
FileInfo myFile = new FileInfo(System.Web.HttpContext.Current.Server.MapPath("Attachments//"+ServerFileName));
myFile.Delete();
bFlag = true;
}
catch
{}
return bFlag;
}
}
}
现在可以动手编写页面了,如index.aspx的代码如下:
<%@ Page language="c#" Codebehind="index.aspx.cs" AutoEventWireup="false" Inherits="email.index" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>小笨笨的Email发送系统</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
<style type="text/css">BODY { FONT-SIZE: 9pt; BACKGROUND-COLOR: #ffffff }
A:visited { COLOR: #000000; TEXT-DECORATION: none }
A:active { COLOR: #000000; TEXT-DECORATION: none }
A:hover { LEFT: 1px; COLOR: #000000; POSITION: relative; TOP: 1px; TEXT-DECORATION: underline }
A:link { COLOR: #000000; TEXT-DECORATION: none }
TD { FONT-SIZE: 9pt;"宋体" }
.button { BORDER-RIGHT: #b2c2d7 1px solid; BORDER-TOP: #b2c2d7 1px solid; FONT-SIZE: 9pt; BORDER-LEFT: #b2c2d7 1px solid; COLOR: #205064; BORDER-BOTTOM: #b2c2d7 1px solid; BACKGROUND-COLOR: #fef8ef }
</style>
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<TABLE id="Table1" cellSpacing="1" cellPadding="1" width="630" border="0" align="center">
<TBODY>
<tr>
<td colspan="4" align="center"><font size="+1"><b>小笨笨的邮件发送系统<b></font></td>
</tr>
<TR>
<TD>收件人:</TD>
<TD colspan="3">
<asp:textbox id="tbTo" runat="server" Width="250px"></asp:textbox></TD>
</TR>
<TR>
<TD>抄送</TD>
<TD>
<asp:TextBox id="tbCc" runat="server" Width="250px"></asp:TextBox></TD>
<TD>暗送:</TD>
<TD>
<asp:TextBox id="tbBcc" runat="server" Width="250px"></asp:TextBox></TD>
</TR>
<TR>
<TD>主题:</TD>
<TD colspan="3">
<asp:textbox id="tbSubject" runat="server" Width="400px"></asp:textbox></TD>
</TR>
<TR>
<TD colspan="2">邮件正文:</TD>
<TD colspan="2">优先级别:
<asp:DropDownList id="ddlPriority" runat="server">
<asp:ListItem Value="High">高</asp:ListItem>
<asp:ListItem Value="Normal" Selected="True">中</asp:ListItem>
<asp:ListItem Value="Low">低</asp:ListItem>
</asp:DropDownList>HTML邮件:
<asp:DropDownList id="ddlIfHtml" runat="server">
<asp:ListItem Value="true">HTML邮件</asp:ListItem>
<asp:ListItem Value="false">文本邮件</asp:ListItem>
</asp:DropDownList></TD>
</TR>
<TR>
<TD colspan="4">
<asp:textbox id="tbBody" runat="server" Width="600px" TextMode="MultiLine" Height="250px"></asp:textbox></TD>
</TR>
<TR>
<TD>
<FONT>附件:</FONT></TD>
<TD colspan="3"><INPUT id="upfile" type="file" name="upfile" runat="server">
<asp:Button id="btUpFile" runat="server" Text="上传"></asp:Button>
<asp:button id="btSend" runat="server" Text="发送"></asp:button></TD>
</TR>
<TR>
<TD>
<FONT>已上传附件:</FONT></TD>
<TD colspan="3">
<asp:DropDownList id="ddlUpFile" runat="server"></asp:DropDownList>
<asp:Button id="btDelFile" runat="server" Text="删除" Enabled="False"></asp:Button></TD>
</TR>
<TR>
<TD align="right" colspan="4">小笨笨邮件发送系统,仅供参考,转载请注明出处。<br>
<a href="http://smallfools.blog.hexun.com/default.html" target="_blank">http://smallfools.blog.hexun.com/default.html</a></TD>
</TR>
</TBODY>
</TABLE>
</form>
</body>
</HTML>
而index.aspx.cs的代码如下:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace email
{
/// <summary>
/// index 的摘要说明。
/// </summary>
public class index : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox tbTo;
protected System.Web.UI.WebControls.TextBox tbCc;
protected System.Web.UI.WebControls.TextBox tbBcc;
protected System.Web.UI.WebControls.TextBox tbSubject;
protected System.Web.UI.WebControls.DropDownList ddlPriority;
protected System.Web.UI.WebControls.DropDownList ddlIfHtml;
protected System.Web.UI.WebControls.TextBox tbBody;
protected System.Web.UI.WebControls.DropDownList ddlUpFile;
protected System.Web.UI.WebControls.Button btUpFile;
protected System.Web.UI.WebControls.Button btSend;
protected System.Web.UI.WebControls.Button btDelFile;
protected System.Web.UI.HtmlControls.HtmlInputFile upfile;
protected smallfoolsEmail myemail = new smallfoolsEmail();
private void Page_Load(object sender, System.EventArgs e)
{
if (!this.IsPostBack)
{
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btUpFile.Click += new System.EventHandler(this.btUpFile_Click);
this.btSend.Click += new System.EventHandler(this.btSend_Click);
this.btDelFile.Click += new System.EventHandler(this.btDelFile_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void btUpFile_Click(object sender, System.EventArgs e)
{
if (this.upfile.PostedFile.ContentLength != 0)
{
if (myemail.UpFile(this.upfile.PostedFile))
{
string clientFileName = this.upfile.PostedFile.FileName;
string[] strTemp = clientFileName.Split('//');
string ServerFileName = strTemp[strTemp.Length-1].ToString();
this.ddlUpFile.Items.Add(new ListItem(this.upfile.PostedFile.FileName,ServerFileName));
if (this.ddlUpFile.Items.Count>0)
{
this.btDelFile.Enabled = true;
}
else
{
this.btDelFile.Enabled = false;
}
}
else
{
Page.RegisterClientScriptBlock("err","<script language=javascript>alert('上传附件失败')</script>");
}
}
}
private void btDelFile_Click(object sender, System.EventArgs e)
{
if (myemail.DelFile(this.ddlUpFile.SelectedValue))
{
this.ddlUpFile.Items.Remove(this.ddlUpFile.Items[this.ddlUpFile.SelectedIndex]);
if (this.ddlUpFile.Items.Count>0)
{
this.btDelFile.Enabled = true;
}
else
{
this.btDelFile.Enabled = false;
}
Page.RegisterClientScriptBlock("OK","<script language=javascript>alert('删除成功')</script>");
}
else
{
Page.RegisterClientScriptBlock("err","<script language=javascript>alert('删除失败')</script>");
}
}
private void btSend_Click(object sender, System.EventArgs e)
{
string To = this.tbTo.Text.Trim();
string Cc = this.tbCc.Text.Trim();
string Bcc = this.tbBcc.Text.Trim();
string Subject = this.tbSubject.Text.Trim();
string Body = this.tbBody.Text;
string Priority = this.ddlPriority.SelectedValue;
bool IsHtml = bool.Parse(this.ddlIfHtml.SelectedValue);
string[] Attachments = new string[this.ddlUpFile.Items.Count];
for (int i=0;i<this.ddlUpFile.Items.Count;i++)
{
Attachments[i] = this.ddlUpFile.Items[i].Value;
}
if (myemail.SendEmail(To,Cc,Bcc,Subject,Body,Priority,IsHtml,Attachments))
{
Page.RegisterClientScriptBlock("ok","<script language=javascript>alert('发送成功')</script>");
}
else
{
Page.RegisterClientScriptBlock("ok","<script language=javascript>alert('发送失败')</script>");
}
}
}
}
参考:http://smallfools.blog.hexun.com/default.html