邮件发送:
如下图:
A:页面代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>邮件发送</title>
</head>
<body>
<form id="form1" runat="server">
<div>
发件人:<asp:TextBox ID="txtfromAddress" runat="server"></asp:TextBox>
<br />
收件人:<asp:TextBox ID="txtMailAddress" runat="server"></asp:TextBox>
<br />
抄 送:
<asp:TextBox ID="txtCopyAddress" runat="server" Width="400px"></asp:TextBox>
<br />
主 题:
<asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>
<br />
内 容:
<asp:TextBox ID="txtMailContents" runat="server" Height="413px" TextMode="MultiLine"
Width="404px"></asp:TextBox>
<br />
附 件:
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Label ID="lblReturnMessage" runat="server" Text=" " ForeColor="Red"></asp:Label>
<asp:Button ID="butSend" runat="server" Text="发送" OnClick="butSend_Click" />
</div>
</form>
</body>
</html>
B:后台代码:
public void SendMail()
{
try
{
//var from = new MailAddress("Jerry219@126.com"); //邮件的发件人,后面为显示的名字
var from = new MailAddress(this.txtfromAddress.Text); //邮件的发件人,后面为显示的名字
var mail = new MailMessage();
//设置邮件的标题
mail.Subject = this.txtSubject.Text;
//设置邮件的发件人
mail.From = from;
//多人发送
string[] mailNames = txtCopyAddress.Text.Split(';'); //抄送
foreach (string name in mailNames)
{
if (name != string.Empty)
{
string address = "";
string displayName = "";
if (name.IndexOf('<') > 0)
{
displayName = name.Substring(0, name.IndexOf('<'));
address = name.Substring(name.IndexOf('<') + 1).Replace('>', ' ');
}
else
{
displayName = string.Empty;
address = name.Substring(name.IndexOf('<') + 1).Replace('>', ' ');
}
mail.CC.Add(new MailAddress(address, displayName)); //收件人地址的集合
}
}
//添加附件
var myfiles = new Attachment(FileUpload1.PostedFile.FileName);
mail.Attachments.Add(myfiles);
//设置邮件的内容
mail.Body = txtMailContents.Text;
//设置邮件的格式
mail.BodyEncoding = Encoding.UTF8;
//设置正文是否为HTML格式
mail.IsBodyHtml = true;
//设置邮件的发送级别
mail.Priority = MailPriority.Normal;
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
var client = new SmtpClient();
//设置SMTP的地址,注意:是什么邮箱就应该用相对应的地址
client.Host = "SMTP.126.com";
//设置用于 SMTP 事务的端口,默认的是 25
client.Port = 25;
client.UseDefaultCredentials = false;
//我的邮箱的登录名和密码。就是发送方的用户名和密码,要对应上面的Host地址
client.Credentials = new NetworkCredential("Jerry219@126.com", "******");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
//邮件的正式发送
client.Send(mail);
lblReturnMessage.Text = "邮件发送成功...";
}
catch (Exception ex)
{
lblReturnMessage.Text = "邮件发送失败..." + ex.Message;
}
}
protected void butSend_Click(object sender, EventArgs e)
{
SendMail();
}