天天看点

EWS操作exchange邮件服务器收发邮件

参考资料: http://www.dotblogs.com.tw/wadehuang36/archive/2012/07/04/ews-first.aspx

本範例的主要功能是尋找未讀郵件並下載附件、完成更新成已讀並移動資料夾

view source print ?

01

internal

class

Program

02

{

03

private

static

void

Main(

string

[] args)

04

{

05

ExchangeService es = 

new

ExchangeService(ExchangeVersion.Exchange2007_SP1);

//版本預設值最新版

06

es.Credentials = 

new

WebCredentials(

"username"

"password"

"domain"

);

07

//es.Credentials = new ClientCertificateCredentials(x509); 也可以使用憑證登入

08

09

es.Url = 

new

Uri(

"https://server/EWS/Exchange.asmx"

); // Server路徑

10

11

Folder processedFolder = GetFolder(es);

12

SearchFilter search = 

new

SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, 

false

); 

//使用欄位搜尋

13

//string search = "From:Wade AND Subject:EWS"; //也支援搜尋語法,但語法沒有IsRead欄位

14

15

//找出 10筆 Inbox 下的未讀郵件

16

foreach

(EmailMessage element 

in

es.FindItems(WellKnownFolderName.Inbox, search, 

new

ItemView(10)))

17

{

18

//跟IMAP一樣,首先只會下載部分基本資料,像Body與Attachments資訊要呼叫Load才會下載

19

element.Load(PropertySet.FirstClassProperties);

20

21

foreach

(FileAttachment item 

in

element.Attachments)

22

{

23

//下載附檔

24

item.Load(

"R:\\"

+ item.Name);

25

}

26

27

//Do Something

28

29

//更新成已讀

30

element.IsRead = 

true

;

31

element.Update(ConflictResolutionMode.AlwaysOverwrite);

32

33

//移動到處理完成資料夾

34

element.Move(processedFolder.Id);

35

}

36

}

37

38

private

static

Folder GetFolder(ExchangeService es)

39

{

40

//取得 處理完成資料夾,如果沒有資料夾就新增

41

SearchFilter search = 

new

SearchFilter.IsEqualTo(FolderSchema.DisplayName, 

"處理完成"

);

42

43

var folder = es.FindFolders(WellKnownFolderName.Inbox, search, 

new

FolderView(1)).FirstOrDefault();

44

if

(folder == 

null

)

45

{

46

folder = 

new

Folder(es);

47

folder.DisplayName = 

"處理完成"

;

48

folder.Save(WellKnownFolderName.Inbox); 

//在Inbox下新增資料夾

49

}

50

51

return

folder;

52

}

53

}

继续阅读