【IT168技术新闻】本篇文章旨在帮助初学者对通过ASP.NET 2.0使用SMTP客户端发送一个具有内嵌图片或对象的email建立基础性概念。
我写这篇文章主要是因为我的一个同僚遇到一个相同的需求,要在应用程序中发送一个包含内嵌图片(而不是作为附件)的email邮件。
代码非常的简单直白。当然,作为一个首要的必备条件你应该能够访问一个邮件服务器。
首先,创建一个MailMessage对象,同时指定发送人和接收人地址。
其次,创建AlternateView来接收文本内容,创建LinkedResource来接收要嵌入的图片或代码。
再次,添加LinkedResource到AlternateView
然后,添加AlternateView到MailMessage
最后,设置SmtpClient,发送email
Collapse Dim msg As New MailMessage("sender mail address", "recipient mail address") msg.Subject = "This is my first email through program" msg.IsBodyHtml = True Dim View As AlternateView Dim resource As LinkedResource Dim client As SmtpClient Dim msgText As New StringBuilder msgText.Append("Hi there,") msgText.Append("Welcome to the new world programming.") msgText.Append("Thanks") msgText.Append("With regards,") msgText.Append("") 'create an alternate view for your mail View = AlternateView.CreateAlternateViewFromString(msgText.ToString(), Nothing, "text/html") 'link the resource to embed resource = New LinkedResource((Server.MapPath("Images\007jvr.gif"))) 'name the resource resource.ContentId = "Image1" 'add the resource to the alternate view View.LinkedResources.Add(resource) 'add the view to the message msg.AlternateViews.Add(View) client = New SmtpClient() client.Host = "smtp.gmail.com" 'specify your smtp server name/ip here 'client.EnableSsl = True 'enable this if your smtp server needs SSL to communicate client.Credentials = New Net.NetworkCredential("username", "pwd") client.Send(msg)
可以从如下网站下载源码:http://www.codeproject.com/vb/net/Email/Project.zip