3 高级程序设计示例
System.Web.Mail 高级示例是一系列的代码示例,并且支持有计划的执行高级 email 操作的注释(commentary)。这里讨论的一些主题不能用 System.Web.Mail 完成, 但是为了完整我们把它们列出来, 这也是因为我曾经在各种各样的 新闻组(newsgroups)和列表(lists)看到过它们。
重要的:当测试这些示例时,总是确保:
1.?有 System.Web.dll 的引用集(reference set)。
2.?如果你用 C#, 确保 将"using System.Web.Mail;" 语句放在代码的顶端。或者如果你用 VB.NET, 确保将"Imports System.Web.Mail"语句放在代码的顶端。
3. 设置正确的 FROM 和 TO 地址。
4. 设置 SmtpMail.SmtpServer 为有效的服务器, 它允许中继(relaying)你的 FROM email address?或者你发送 email 的 IP 地址。
3.1 如何发送非 US-ASCII emails?
起初, email 首次被使用的时候, 它的内容全都是 us-ascii 编码。为了处理不同的语言和字符集, 不同的编码被使用。下例演示了发送非 us-ascii email, 用 Chinese GB2312 字符集作为示例。发送非 us-ascii email 最难的部分,是决定正确的字符集。 至于参考(For reference), 一种易于使用字符集的方法在 aspNetEmail 的web站点可以找到: http://www.aspnetemail.com/charsets.aspx
注意: 这个技术有一个主要的缺陷(pitfall)。 The original email rfcs required that all non us-character sets use the quoted-printable or base64 content transfer encoding (convert all characters above 127, to 2 or more bytes, so the individual byte value is less than 128). Email readers, then take these bytes, and convert them back to the original character set. System.Web.Mail does not encode higher end character sets. Instead, it just sends the characters unencoded (commonly known in the email world as 8 bit encoding). 因此, 如果你的 email recipient's mail server, 或者王冠 , 不支持8位编码, 那么它们将不能收到 email。
THERE IS NO WAY PROGRAMMATIC WAY OF CHECKING FOR THIS. The only way, is make sure the email message is properly encoded using the quoted-printable (preferred) or base64 content transfer encoding. If you are sending a newsletter, this can be a huge problem, because your newsletter will simply not be delivered, and there is a good chance, you will never know it. As an email vender, I've had customer after customer encounter this problem. And it has always been fixed by using the quoted-printable format. Because this cannot be controlled using System.Web.Mail, you will need to use a third party product like aspNetEmail. The bottom line is this: if you need to send emails, using a higher end character set, DO NOT USE System.Web.Mail. Either roll your own component (if you have the time), or purchase a third party product that properly encodes email messages.
For those people that don't have a choice, and have to use System.Web.Mail, the following is a code snippet demonstrating sending a non us-ascii email.
[ C# ]
mail.To = "me@mycompany.com";
mail.From = "you@yourcompany.com";
mail.Subject = "this is a test email.";
mail.Body = "Some Chinese characters or text goes here";
mail.BodyEncoding = System.Text.Encoding.GetEncoding( "GB2312" ); //set the proper character set here SmtpMail.SmtpServer = "localhost"; //your real server goes here SmtpMail.Send( mail );
[ VB.NET ]
mail.To = "me@mycompany.com"
mail.From = "you@yourcompany.com"
mail.Subject = "this is a test email."
mail.Body = "Some Chinese characters or text goes here"
mail.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312") 'set the proper character set here SmtpMail.SmtpServer = "localhost" 'your real server goes here SmtpMail.Send(mail)
3.2 如何发送 web 页(page)?
System.Web.Mail 本生(natively)不支持发送 web 页。 然而, 利用 WebRequest 类, 你可以获得(screen scrape)web 页, 并将作为最终结果的 Html 字符串传递给 MailMessage 类。下例演示了这个技术。
注意: 确保代码片断中引入了 System.Net 和 System.IO 命名空间。
[ C# ]
{
MailMessage mail = new MailMessage();
mail.To = "me@mycompany.com";
mail.From = "you@yourcompany.com";
mail.Subject = "this is a test email.";
string url = "http://www.microsoft.com";
mail.Body = HttpContent( url );
mail.BodyFormat = MailFormat.Html;
mail.UrlContentBase = url;
SmtpMail.SmtpServer = "localhost"; //your real server goes here SmtpMail.Send( mail ); } //screen scrape a page here
private string HttpContent( string url )
{
WebRequest objRequest= System.Net.WebRequest.Create(url); StreamReader sr = new StreamReader( objRequest.GetResponse().GetResponseStream() );
string result = sr.ReadToEnd();
sr.Close();
return result;
}
[ VB.NET ]
Dim mail As New MailMessage()
mail.To = "me@mycompany.com"
mail.From = "you@yourcompany.com"
mail.Subject = "this is a test email."
Dim url As String = http://www.microsoft.com
mail.Body = HttpContent(url)
mail.BodyFormat = MailFormat.Html
mail.UrlContentBase = url
SmtpMail.SmtpServer = "localhost" 'your real server goes here
SmtpMail.Send(mail)
End Sub
'Page_Load
'screen scrape a page here
Private Function HttpContent(url As String) As String
Dim objRequest As WebRequest = System.Net.HttpWebRequest.Create(url)
Dim sr As New StreamReader(objRequest.GetResponse().GetResponseStream())
Dim result As String = sr.ReadToEnd()
sr.Close()
Return result
End Function
3.3 如何在 email 中嵌入(embed)图片?
你不能用 System.Web.Mail 这样做。利用一些像 aspNetEmail?的, 它可以支持自动在 email 中嵌入图片。?
?
3.4 如何发送 website 异常(exception)?
global.asax 类(class)用 Application_Error 方法捕获(capture)错误。?利用 System.Web.Mail, 每当错误发生时网站管理员(webmaster)可以发送 email 给它们自己。
下面的代码片断(snippet)演示了这样技术。
[ C# ]
{
Exception ex = Server.GetLastError();
EmailException( ex );
}
private void EmailException( Exception ex )
{
MailMessage mail = new MailMessage();
mail.To = me@mycompany.com;
mail.From = you@yourcompany.com;
mail.Subject = "An exception occurred.";
mail.Body = ex.ToString();
SmtpMail.SmtpServer = "localhost"; //your real server goes here
SmtpMail.Send( mail );
}
[ VB.NET ]
Protected Sub Application_Error(sender As [Object], e As EventArgs)
Dim ex As Exception = Server.GetLastError()
EmailException(ex)
End Sub
'Application_Error
Private Sub EmailException(ex As Exception)
Dim mail As New MailMessage()
mail.To = me@mycompany.com
mail.From = you@yourcompany.com
mail.Subject = "An exception occurred."
mail.Body = ex.ToString()
SmtpMail.SmtpServer = "localhost" 'your real server goes here SmtpMail.Send(mail)
End Sub
'EmailException
3.5 如何用 s/mime?或者 pgp加密(encrypt)信息(messages)?
你不能。System.Web.Mail 不支持加密(encrypted)信息( messages)。
3.6 如何发送 multipart/related emails?
你不能。System.Web.Mail 不支持 multipart/related 信息( messages)。
3.7 如何发送 multipart/alternative emails?
如果你想直接控制 multipart/alternative email 所有部分的每一部分, 这是不能用 System.Web.Mail 做到的。 然而, 如果你创建了一个 Html?格式的 email, 并且System.Web.Mail 使用 CDO.Message 动态连接库, 那么 alternative text/plain?部分将被自动创建。
3.8 如何验证以发送 email?
如果你用的是 .NET Framework 1.0, 那么这项功能不被支持。然而,在 1.1 版本中, 添加了 MailMessage.Fields 属性。它允许访问根本的(underlying) CDO.Message 域。
下面这个例子演示了发送你的用户名和密码给 SMTP?服务器以提供验证(authentication)。
[ C# ]
MailMessage mail = new MailMessage();
mail.To = me@mycompany.com;
mail.From = you@yourcompany.com;
mail.Subject = "this is a test email.";
mail.Body = "Some text goes here";
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "my_username_here"); //set your username here
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "super_secret"); //set your password here
SmtpMail.SmtpServer = "mail.mycompany.com"; //your real server goes here SmtpMail.Send( mail );
}
[ VB.NET ]
Private Sub Page_Load(sender As Object, e As System.EventArgs)
Dim mail As New MailMessage()
mail.To = me@mycompany.com
mail.From = you@yourcompany.com
mail.Subject = "this is a test email."
mail.Body = "Some text goes here"
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1") 'basic authentication
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "my_username_here") 'set your username here
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "super_secret") 'set your password here
SmtpMail.SmtpServer = "mail.mycompany.com" 'your real server goes here SmtpMail.Send(mail)
End Sub
'Page_Load