ASP.NET使用SMTP协议简单的发送邮件(支持附件)
引入下面两个名称空间
using System.Net.Mail;
using System.Net;
前台页面代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
发送人:<asp:TextBox ID="txtFrom" runat="server"></asp:TextBox>
<br />
收件人:<asp:TextBox ID="txtTo" runat="server"></asp:TextBox>
<br />
主题:<asp:TextBox ID="txtTheme" runat="server"></asp:TextBox>
<br />
附件:<asp:FileUpload ID="fpAttachment"
runat="server" />
<br />
内容:<asp:TextBox ID="txtContent" runat="server" Rows="20" TextMode="MultiLine"
Width="300px"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="发送" onclick="Button1_Click" />
</div>
</form>
</body>
</html>
后台C#代码:
protected void Button1_Click(object sender, EventArgs e)
{
//测试通过,能发送带有附件的邮件
string from = txtFrom.Text.Trim(); //发件人
string to = txtTo.Text.Trim();//收件人
string theme = txtTheme.Text.Trim();//主题
//string file = fpAttachment.FileName;//附件文件名
string file =fpAttachment.PostedFile.FileName;//附件文件路径(包含文件名)
string content = txtContent.Text; //邮件内容
MailMessage messge = new MailMessage(from,to); //邮件消息实例
messge.Body = content;
messge.Subject = theme;
messge.IsBodyHtml = true;
messge.Priority = MailPriority.High;//邮件优先级别
messge.Attachments.Add(new Attachment(file));
SmtpClient client = new SmtpClient(); //Smtp协议
client.Host = "smtp.163.com"; //发送人的Smtp主机名称或IP地址,实例为163邮箱的Smtp地址
client.Credentials = new NetworkCredential("cpeng0907@163.com", "发送邮箱的密码");//验证发件人的身份凭据
client.Send(messge);
messge.Attachments.Dispose();
}
由于时间关系只做简单的测试(已通过),暂时没有测试发送多人,以及抄送功能,如有不足请各位网友指出,共同学习,谢谢

浙公网安备 33010602011771号