利用System.Net.Mail 实现电子邮件发送到简单邮件传输协议 (SMTP) 服务器进行传送.
1.修改webconfig文件
<system.net>
<mailSettings>
<smtp>
<network host="smtp host" port="25" userName="username" password="password"/>
</smtp>
</mailSettings>
</system.net>
2. 点击button实现邮件发送
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void SendEmail(string from, string to, string bcc, string cc, string subject, string body, string mAttachment)
{
MailMessage NewEmail = new MailMessage();
// 表示电子邮件发件人或收件人的地址
//MailAddress from = new MailAddress("ben@contoso.com", "Ben Miller");
NewEmail.From = new MailAddress(from,from);
NewEmail.To.Add(new MailAddress(to));
// 你也可以添加一个地址到集合 NewEmail.To = new MailAddressCollection().Add(new MailAddress(to));
NewEmail.Bcc.Add(new MailAddress(bcc));
if (!String.IsNullOrEmpty(cc))
{
NewEmail.CC.Add(new MailAddress(cc));
}
NewEmail.Subject = subject;
NewEmail.Body = body;
Attachment MsgAttach = new Attachment((mAttachment));
NewEmail.Attachments.Add(MsgAttach);
NewEmail.IsBodyHtml = true;
NewEmail.Priority = MailPriority.Normal;
SmtpClient mSmtpClient = new SmtpClient();
mSmtpClient.Send(NewEmail);
}
protected void Button1_Click(object sender, EventArgs e)
{
string from = "发件人";
string to = "收件人";
string bcc = "密件抄送 (BCC)";
string cc = "抄送 (CC)";
string subject = "主题";
string body = "邮件正文";
string mAttachment = "附件";
SendEmail(from, to, bcc, cc, subject, body, mAttachment);
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void SendEmail(string from, string to, string bcc, string cc, string subject, string body, string mAttachment)
{
MailMessage NewEmail = new MailMessage();
// 表示电子邮件发件人或收件人的地址
//MailAddress from = new MailAddress("ben@contoso.com", "Ben Miller");
NewEmail.From = new MailAddress(from,from);
NewEmail.To.Add(new MailAddress(to));
// 你也可以添加一个地址到集合 NewEmail.To = new MailAddressCollection().Add(new MailAddress(to));
NewEmail.Bcc.Add(new MailAddress(bcc));
if (!String.IsNullOrEmpty(cc))
{
NewEmail.CC.Add(new MailAddress(cc));
}
NewEmail.Subject = subject;
NewEmail.Body = body;
Attachment MsgAttach = new Attachment((mAttachment));
NewEmail.Attachments.Add(MsgAttach);
NewEmail.IsBodyHtml = true;
NewEmail.Priority = MailPriority.Normal;
SmtpClient mSmtpClient = new SmtpClient();
mSmtpClient.Send(NewEmail);
}
protected void Button1_Click(object sender, EventArgs e)
{
string from = "发件人";
string to = "收件人";
string bcc = "密件抄送 (BCC)";
string cc = "抄送 (CC)";
string subject = "主题";
string body = "邮件正文";
string mAttachment = "附件";
SendEmail(from, to, bcc, cc, subject, body, mAttachment);
}
}