csharp Exchange邮件操作

双子民
2023-12-01

csharp Exchange邮件操作

准备

安装nuget包:Microsoft.Exchange.WebServices

使用命名空间 Microsoft.Exchange.WebServices.Data

    using Microsoft.Exchange.WebServices.Data;

连接服务器

    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
    service.Credentials = new WebCredentials("yue_zhou", "youarefat0A", "intsig");
    service.AutodiscoverUrl("yue_zhou@intsig.net");

收件箱


    Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
    Console.WriteLine(inbox.DisplayName);       // 输出"收件箱"

    var subFolders =  inbox.FindFolders(new FolderView(100)).Folders;
    foreach(var folder in subFolders)
    {
        Console.WriteLine("\t" + folder.DisplayName);
    }

    var emails = inbox.FindItems(new ItemView(100));
    foreach(EmailMessage email in emails)
    {
        Console.WriteLine($"email: {email.DateTimeReceived}\t{email.Subject}");
    }

发信人地址

    var nd = service.ResolveName(email.From.Address);
    foreach(var nr in nd)
    {
        var rt = nr.Mailbox.RoutingType;
        if(rt == "SMTP")
        {
            Console.WriteLine(nr.Mailbox.Address)
        }
    }

获取附件文件

    EmailMessage email = ...
    service.LoadPropertiesForItems(new Item[] { email }, BasePropertySet.FirstClassProperties);
    foreach(var attachment in email.Attachments)
    {
        if(attachment is FileAttachment)
        {
            var fileAttachment = attachment as FileAttachment;
            string saveFileName = "abc.txt";
            fileAttachment.Load(saveFileName);  // save attachement to file
        }
    }

移动邮件

	EmailMessage email = ...
	Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
	string targetFolderName = "目标文件夹";
	var subFolders = inbox.FindFolders(new FolderView(inbox.ChildFolderCount)).Folders;
	FolderId targetFolderId;
	foreach(var folder in subFolders)
    {
		if(folder.DisplayName == targetFolderName)
		{
			targetFolderId = folder.Id;
			break;
		}
    }
	email.Move(inbox.Id);

读取邮件内容

	EmailMessage email = ...
	email.Load();	// 从服务器获取内容
	Console.WriteLine(email.Body.Text);	// 输出邮件内容,一般为HTML格式

发送邮件

	EmailMessage email = new EmailMessage(service);
    email.ToRecipients.Add("allenchou13@163.com");
    email.Subject = "test exchange email";
    email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API.");
    email.Attachments.AddFileAttachment(@"C:\Users\yue_zhou\Desktop\新建 Microsoft Excel 工作表.xlsx");
    email.Send();

回复邮件

    var ews_email = EmailMessage.Bind(service, new ItemId((string)email_row["ews_emailid"]));
    ews_email.Reply(new MessageBody() { Text = replyText.ToString(), BodyType = BodyType.HTML }, true);

参考

微软Exchange Server文档

 类似资料: