本文主要是以.NET下怎么实现发送E-Mail作为示例分析讲解,故在示例程序里有许多涉及到.Net.Mail之外的内容都没做.最近比较忙没太多的时候去完善其功能,有兴趣的朋友可以下载源码去完善下.这不是一个什么大的软件,也不是什么很特别的东西,我写这个文章的目的是让大家一起来学习.NET下发送E-mail的实现,希望这篇文章可以帮助到还没搞清楚怎么实现发送邮件的朋友,对于已经会的或是这方面的牛人的前辈们看了本文请留下宝贵的建议.
本程序是采用.NET框架下的Mail类来完成邮件的发送操作的,里面收件人mail地址我采用的xml来存储,这涉及到了xml的读写操作,在添加附件的时候涉及到对话框的应用.分析于此,首先我门需要引用相宜的名称空间,即:
1
using System.Net.Mail;
2
using System.Xml;
3
using System.IO;

2

3

一. 首先来看看最终的运行效果(可以从界面层上理解到程序的结构)
二. 下面来看看实现发送e-mail功能的代码,代码如下所示:





































三. 设置收件人的邮件地址
这里我采用XML文件存储,Setting.xml定义如下:
1
<?xml version="1.0" encoding="utf-8" ?>
2
<mail>
3
<list>beniao123@126.com</list>
4
<list>beniao277@163.com</list>
5
<list>beniao133@126.com</list>
6
<list>beniao133@126.com</list>
7
</mail>

2

3

4

5

6

7

将Setting.xml里的数据读取到winfrom的界面控件ListBox上进行绑定,这里我定义了一个私有方法DataBindListBox()
然后在窗体form_load()里调用,方法定义如下:
1
private void DataBindListBox()
2
{
3
//清空现有绑定数据
4
this.lbQuester.Items.Clear();
5
//通过ADO.NET的DataSet对象的ReadXml()方法读取联系人邮件地址
6
DataSet ds = new DataSet();
7
ds.ReadXml("http://www.cnblogs.com/Setting.xml");
8
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
9
{
10
object obj = ds.Tables[0].Rows[i][0].ToString() as object;
11
this.lbQuester.Items.Add(obj);
12
}
13
}

2

3

4

5

6

7

8

9

10

11

12

13

四. 从文本文件导入收件人邮件地址
1
/// <summary>
2
/// 读取文本文件的方法
3
/// </summary>
4
/// <param name="filePath"></param>
5
/// <returns></returns>
6
private DataTable ReadInFromTxt(string filePath)
7
{
8
FileStream fs = new FileStream(filePath, FileMode.Open);
9
StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding("GB2312"));
10
DataTable dt = new DataTable();
11
while (!sr.EndOfStream)
12
{
13
//将数据添加到DataTable
14
//

15
//

16
//this.lbQuester.Items.Add(sr.ReadLine().Trim().ToString()); 直接添加到列表项
17
}
18
WriteXml("http://www.cnblogs.com/Setting.xml", dt); //将读取到的数据写入Setting.xml
19
DataBindListBox(); //刷新列表项
20
return dt;
21
}

2

3

4

5

6

7

8

9

10

11

12

13

14



15



16

17

18

19

20

21

五. 将从文本文件读取的数据写入Setting.xml,见于时间关系,这方法的代码没完成,有兴趣的朋友可以帮忙完善下.谢谢.
1
/// <summary>
2
/// 将文本文件里的数据导入操作
3
/// 并写入Setting.xml文件里
4
/// 同时更新窗体上ListBox的Items
5
/// </summary>
6
/// <param name="filePath">xml文件地址</param>
7
/// <param name="dTable">从文本文件里读取的数据</param>
8
private void WriteXml(string filePath,DataTable dTable)
9
{
10
XmlDocument doc = new XmlDocument();
11
doc.Load(@filePath);
12
XmlElement rootNode = doc.DocumentElement;
13
//


14
//
.代码略
15
doc.Save(filePath);
16
//刷新ListBox的列表项
17
DataBindListBox();
18
}

2

3

4

5

6

7

8

9

10

11

12

13




14


15

16

17

18

本文就写于此,当然文中还有很多地方都不够完善,但是我在开篇之时就说过,本文主要是以解说.NET下怎么实现发送E-Mail,由于时间关系,部分功能就没作详细.........
源代码下载