使用ASP.NET发送邮件 x

essage类结合在一起使用,用于给电子邮件添加附件。该类可以使用字符类型(String)和数据流(Stream)的形式创建附件。支持数据流的形式就意味着能用任何的文件格式作为附件,例如TXT格式或DOC格式。

18.5.2  语法定义

Attachment类的语法定义如下:

public class Attachment : AttachmentBase

该类的构造函数有6个重载,下面演示创建一个Attachment类的实例的两种常用方式。

Attachment Item = new Attachment (@“c:\附件.txt”, MediaTypeNames.Text.Plain);

以上这种情况,第一个参数为附件的路径,第二个参数为附件的MIME内容标头信息,简单来说就是标明文件的格式。

System.IO.FileInfo file =new System.IO.FileInfo(@"C:\附件.txt");

System.IO.FileStream stream = file.OpenRead();

Attachment item = new Attachment(stream, MediaTypeNames.Text.Plain);

第二种情况,第一个参数以数据流的方式传入。数据流可以从文件中读出,也可以从数据库中读出。第二个参数跟上一种情况相同。

18.5.3  方法详解

除 了通过new关键字实例化一个Attachment类对象外,还可以用Attachment类提供的静态方法 CreateAttachmentFromString来创建该类的一个实例。下面的代码演示了如何使用 CreateAttachmentFromString方法:

Attachment Item =Attachment.CreateAttachmentFromString(@“c:\附件.txt”, MediaTypeNames.Text.Plain);

18.5.4  属性详解

Attachment类通过一些属性来访问附件的内容,其中几个重要属性及其说明如表18-5所示。

表18-5  Attachment类的主要属性及其说明

    

    

    

    

ContentDisposition

附件的MIME内容处置

ContentType

附件内容的类型

ContentStream

附件的流数据

Name

附件内容的类型名称

下面用例子来说明Attachment类属性的用法。

static void Main(string[] args)

   {

       Attachment content = new Attachment(@"c:\附件.txt", MediaTypeNames.Text.Plain);

       ContentDisposition disposition = content.ContentDisposition;

       disposition.FileName = "文本附件";

       Console.WriteLine("附件内容名称:{0} 类型名称:{1} 附件文件名: {2}",content.Name,content.ContentType.MediaType,content.ContentDisposition.FileName);}

上面的代码输出结果为:

附件内容名称:附件.txt 类型名称:text/plain 附件文件名:文本附件

18.5.5  典型应用:使用Attachment类添加电子邮件的附件

下面演示如何使用Attachment类为电子邮件添加一个文本附件,代码如下:

static void Main(string[] args)

      {

          SmtpClient client = new SmtpClient();

          //此处省略 SmtpClient 类的其他属性设置

          MailMessage message = new MailMessage();

          message.Body = "这是邮件的正文部分";

          //设置正文的编码形式.这里的设置为取系统默认编码

          message.BodyEncoding = System.Text.Encoding.Default;

          message.From = new MailAddress("FromMailBox@Sina.com");

          message.IsBodyHtml = false;

          message.ReplyTo = new MailAddress("FromMailBox@Sina.com");

          message.Sender = new MailAddress("FromMailBox@Sina.com");

          message.Subject = "这是邮件的主题";

          //添加附件

          Attachment content = new Attachment(@"c:\附件.txt", MediaTypeNames.Text.Plain);

          message.Attachments.Add(content);

          //设置主题的编码形式.这里的设置为取系统默认编码

          message.SubjectEncoding = System.Text.Encoding.Default;

          client.Send(message); //发送邮件

          Console.WriteLine("发送成功!");

      }

18.6  应用实例:发送电子邮件程序

结合本章学习的内容,下面将实现一个电子邮件发送程序,详细步骤如下。

*     在VS2005中创建一个Windows应用程序,命名为“SendMail”。

*     打开默认生成的Form1的设计界面。从工具箱中选择控件,把界面设计成图18-3所示的样式。

使用ASP.NET发送邮件 - Dragon - everyday happy

图18-3  示例界面设计

*     设置控件的属性,其中主要控件的属性设置如表18-6所示。

表18-6  主要控件属性

    

    

Name属性

    

TextBox

收件人地址

txtAddress

 

TextBox

标题

txtTitle

 

TextBox

内容

txtContent

Mutiline属性为True

TextBox

附件

txtAttachment

ReadOnly属性为True

Button

发送

btSend

 

Button

添加附件

btAddAttachment

 

*     双击“发送”按钮,打开代码视图,在代码窗口的顶部添加对命名空间的引用,代码如下:

using System.Net.Mail;

使用ASP.NET发送邮件 - Dragon - everyday happy     在“发送”按钮的Click事件中,添加对SendMail函数的调用,代码如下:

private void btSend_Click(object sender, EventArgs e)

{

    if (SendMail())

    {

        MessageBox.Show("发送成功");

    }

}

使用ASP.NET发送邮件 - Dragon - everyday happy   编写SendMail函数,代码如下:

//发送电子邮件成功返回True,失败返回False

private bool SendMail()

{

    MailAddress from = new MailAddress("FromMailBox@Sina.com ", "测试账号");

    //收件人地址

    MailAddress to = new MailAddress(this.txtAddress.Text, "hello");

    MailMessage message = new MailMessage(from, to);

    //添加附件,判断文件存在就添加

    if(System.IO.File.Exists(this.txtAttachment.Text))

    {

       Attachment item =new Attachment(this.txtAttachment.Text, MediaTypeNames.Text.Plain);

        message.Attachments.Add(item);

    }

    message.Subject = this.txtTitle.Text; // 设置邮件的标题

    message.Body = this.txtContent.Text; //发送邮件的正文

    message.BodyEncoding = System.Text.Encoding.Default;

    MailAddress other = new MailAddress("otherPerson@163.com");

    message.CC.Add(other); //添加抄送人

    //创建一个SmtpClient 类的新实例,并初始化实例的SMTP 事务的服务器

    SmtpClient client = new SmtpClient(@"smtp.Sina.com");

    client.DeliveryMethod = SmtpDeliveryMethod.Network;

    client.UseDefaultCredentials = false;

    client.EnableSsl = false;

    //身份认证

    client.Credentials = new System.Net.NetworkCredential("FromMailBox@Sina.com", "*****");

    bool ret =true; //返回值

    try

    {

        client.Send(message);

     }

    catch (SmtpException ex)

    {

        MessageBox.Show(ex.Message);

        ret =false;

    }

    catch(Exception ex2)

    {

        MessageBox.Show(ex2.Message);

        ret = false;

    }

    return ret;

}

使用ASP.NET发送邮件 - Dragon - everyday happy   按F5键运行程序,测试邮件的发送功能。

技巧:为了简化程序,上列中用于发送邮件的地址HardCode(硬代码)了,读者可以增加输入框来录入发送地址、密码和SMTP服务器等信息,让程序变得更灵活。

18.7  小结

本 章主要介绍了如何使用System.Net.Mail命名空间下的类。其中,SmtpClient类可以发送电子邮件,MailMessage类可以丰富 电子邮件的内容,MailAddress类可以设置电子邮件的收件人或发件人的电子邮件地址,Attachment类可以为邮件添加附件。

通过对本章的学习,读者可以掌握发送电子邮件的技巧,还能为应用程序提供自动发送电子邮件的功能。

posted @ 2013-03-11 12:41  天涯海角路  阅读(167)  评论(0)    收藏  举报