日期:2010-12-25  浏览次数:20428 次

用System.Web.Mail发送邮件,适用于.net1.1,.net2.0请用System.Net.Mail

先引用System.Web
1,发送简单邮件
[ C# ]
MailMessage mail = new MailMessage();mail.To = "me@mycompany.com";mail.From = "you@yourcompany.com";mail.Subject = "this is a test email.";mail.Body = "this is my test email body";SmtpMail.SmtpServer = "localhost";  //your real server goes hereSmtpMail.Send( mail );

[ VB.NET ]
Dim mail As New MailMessage()mail.To = "me@mycompany.com"mail.From = "you@yourcompany.com"mail.Subject = "this is a test email."mail.Body = "this is my test email body"SmtpMail.SmtpServer = "localhost" 'your real server goes hereSmtpMail.Send(mail)这里的smtpserver只能是那些不需要验证的smtp服务器,像126,sina,yahoo等等的邮箱,都需要验证,所以不能用。用这些邮箱发信后面会讲到2,发送Html邮件[ C# ] MailMessage mail = new MailMessage();mail.To = "me@mycompany.com";mail.From = "you@yourcompany.com";mail.Subject = "this is a test email.";mail.BodyFormat = MailFormat.Html;mail.Body = "this is my test email body.<br><b>this part is in bold</b>";SmtpMail.SmtpServer = "localhost";  //your real server goes hereSmtpMail.Send( mail );
 [ VB.NET ] Dim mail As New MailMessage()mail.To = "me@mycompany.com"mail.From = "you@yourcompany.com"mail.Subject = "this is a test email."mail.BodyFormat = MailFormat.Htmlmail.Body = "this is my test email body.<br><b>this part is in bold</b>"SmtpMail.SmtpServer = "localhost" 'your real server goes hereSmtpMail.Send(mail)

3,发送附件
[ C# ]
MailMessage mail = new MailMessage();mail.To = "me@mycompany.com";mail.From = "you@yourcompany.com";mail.Subject = "this is a test email.";mail.Body = "this is my test email body.";MailAttachment attachment = new MailAttachment( Server.MapPath( "test.txt" ) ); //create the attachmentmail.Attachments.Add( attachment ); //add the attachmentSmtpMail.SmtpServer = "localhost";  //your real server goes hereSmtpMail.Send( mail );

[ VB.NET ]
Dim mail As New MailMessage()mail.To = "me@mycompany.com"mail.From = "you@yourcompany.com"mail.Subject = "this is a test email."mail.Body = "this is my test email body."Dim attachment As New MailAttachment(Server.MapPath("test.txt")) 'create the attachmentmail.Attachments.Add(attachment) 'add the attachmentSmtpMail.SmtpServer = "localhost" 'your real server goes hereSmtpMail.Send(mail)
4,修改发件人和收件人的名称比如发件人的地址是abc@126.com,我们用outlook收到信,From一栏里将直接显示abc@126.com.能不能在From一栏里显示友好一点的名字呢?比如显示Tony Gong方法如下:[ C# ] MailMessage mail = new MailMessage();mail.To = "\"John\" <me@mycompany.com>";mail.From = "\"Tony Gong\" <you@yourcompany.com>";mail.Subject = "this is a test email.";mail.Body = "this is my test email body.";SmtpMail.SmtpServer = "localhost";  //your real server goes hereSmtpMail.Send( mail );
 [ VB.NET ] Dim mail As New MailMessage()mail.To = """John"" <me@mycompany.com>"mail.From = """Tony Gong"" <you@yourcompany.com>"mail.Subject = "this is a test email."mail.Body = "this is my test email body."SmtpMail.SmtpServer = "localhost" 'your real server goes hereSmtpMail.Send(mail)
5,发送给多人
[