[C#]exchange发送,收件箱操作类

时间:2021-10-02 04:42:37

最近项目中需要用到exchange的操作,就参照msdn弄了一个简单的操作类。目前先实现了,发送邮件和拉取收件箱的功能,其他的以后在慢慢的添加。

using Microsoft.Exchange.WebServices.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks; namespace WebSite.Utilities.Mail
{
/// <summary>
/// exchange邮件客户端类
/// </summary>
public class ExChangeMailClient
{
/// <summary>
/// exchange服务对象
/// </summary>
private static ExchangeService _exchangeService = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
/// <summary>
/// 获取收件箱
/// </summary>
/// <param name="userId">当前用户名</param>
/// <param name="pwd">密码</param>
/// <param name="domain">域</param>
/// <param name="pageSize">一次加载的数量</param>
/// <param name="offset">偏移量</param>
/// <returns></returns>
public static List<Email> GetInbox(string userId, string pwd, string domain, int pageSize, int offset)
{
try
{
if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(pwd) || string.IsNullOrEmpty(domain))
{
throw new ArgumentNullException("当前用户信息为空,无法访问exchange服务器");
}
List<Email> lstEmails = new List<Email>();
_exchangeService.Credentials = new NetworkCredential(userId, pwd, domain);
_exchangeService.Url = new Uri(WebConfig.ExchangeServerUrl);
ItemView view = new ItemView(pageSize, offset);
FindItemsResults<Item> findResults = _exchangeService.FindItems(WellKnownFolderName.Inbox, SetFilter(), view);
foreach (Item item in findResults.Items)
{
item.Load(PropertySet.FirstClassProperties);

//转化为EmailMessage获取 获取邮件详情
var currentEmail = (Microsoft.Exchange.WebServices.Data.EmailMessage)(item);
List<string> ccRecipientsEmailLists = new List<string>();
List<string> bccRecipientsEmailLists = new List<string>();
foreach (var cc in currentEmail.CcRecipients)
{
ccRecipientsEmailLists.Add(cc.Address);
}
foreach (var bcc in currentEmail.BccRecipients)
{
bccRecipientsEmailLists.Add(bcc.Address);
}
lstEmails.Add(new Email()
{
ExchangeItemId = item.Id.ChangeKey,
body = item.Body.Text,
Mail_cc = string.Join(";", ccRecipientsEmailLists.ToArray()),
Mail_bcc = string.Join(";", bccRecipientsEmailLists.ToArray()),
Mail_from = currentEmail.From.Address,
IsRead = item.IsNew,
Subject = item.Subject,
CreateOn = item.DateTimeCreated
});

                }
return lstEmails;
}
catch (Exception ex)
{ throw ex;
} } /// <summary>
/// 根据用户邮件地址返回用户的未读邮件数
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public static int GetUnReadMailCountByUserMailAddress(string userId, string pwd, string domain, string email)
{
int unRead = ;
try
{
_exchangeService.Credentials = new NetworkCredential(userId, pwd, domain);
_exchangeService.Url = new Uri(WebConfig.ExchangeServerUrl);
_exchangeService.ImpersonatedUserId = new Microsoft.Exchange.WebServices.Data.ImpersonatedUserId(Microsoft.Exchange.WebServices.Data.ConnectingIdType.SmtpAddress, email); unRead = Microsoft.Exchange.WebServices.Data.Folder.Bind(_exchangeService, Microsoft.Exchange.WebServices.Data.WellKnownFolderName.Inbox).UnreadCount;
}
catch (Exception ex)
{
throw ex;
}
return unRead;
}
/// <summary>
/// 过滤器
/// </summary>
/// <returns></returns>
private static SearchFilter SetFilter()
{
List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
//searchFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
//searchFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true));
//筛选今天的邮件
SearchFilter start = new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeCreated, Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00")));
SearchFilter end = new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeCreated, Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59")));
searchFilterCollection.Add(start);
searchFilterCollection.Add(end);
SearchFilter filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection.ToArray());
return filter;
}
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="email"></param>
/// <returns></returns>
public static void SendMail(Email email, string userId, string pwd, string domain)
{
try
{
_exchangeService.Credentials = new NetworkCredential(userId, pwd, domain);
_exchangeService.Url = new Uri(WebConfig.ExchangeServerUrl);
//发送人
Mailbox mail = new Mailbox(email.Mail_from);
//邮件内容
EmailMessage message = new EmailMessage(_exchangeService);
string[] strTos = email.Mail_to.Split(';');
//接收人
foreach (string item in strTos)
{
if (!string.IsNullOrEmpty(item))
{
message.ToRecipients.Add(item);
}
}
//抄送人
foreach (string item in email.Mail_cc.Split(';'))
{
if (!string.IsNullOrEmpty(item))
{
message.CcRecipients.Add(item);
} }
//邮件标题
message.Subject = email.Subject;
//邮件内容
message.Body = new MessageBody(email.body);
//发送并且保存
message.SendAndSaveCopy(); }
catch (Exception ex)
{
throw new Exception("发送邮件出错," + ex.Message + "\r\n" + ex.StackTrace);
}
}
}
}

[C#]exchange发送,收件箱操作类的更多相关文章

  1. 【排障】Outlook Express 2G收件箱大小限制

    Outlook Express 2G收件箱大小限制 文:铁乐猫 ----------------------------- Outlook Express(以下简称OE)客户端收件箱大于或接近2G时, ...

  2. SendMail发送回执及读取收件箱

    一.SendMail发送有回执提示 1.邮件发送配置 Properties props = new Properties(); String smtp = "smtp.qq.com&quot ...

  3. 通什翡翠商城大站协议邮件群发系统日发20-30万封不打码不换ip不需发件箱100&percnt;进收件箱

    用一种新的技术思维去群发邮件一种不用换IP,不需要任何发件箱的邮件群发方式一种不需要验证码,不需要**代码变量的邮件群发方式即使需要验证码也能全自动识别验证码的超级智能软件教你最核心的邮件群发思维和软 ...

  4. 懒人邮件群发日发50-100万封不打码不换IP不需发件箱大站协议系统营销软件100&percnt;进收件箱

    用一种新的技术思维去群发邮件 一种不用换IP,不需要任何发件箱的邮件群发方式 一种不需要验证码,不需要**代码变量的邮件群发方式 即使需要验证码也能全自动识别验证码的超级智能软件 教你最核心的邮件群发 ...

  5. Android4&period;4 往短信收件箱中插入自定义短信(伪造短信)

    这段时间稍微有点空闲,把前一段学习Android做过的一些小项目整理整理.虽然没有什么工程量很大的项目,但是对于一个新手,解决这些问题还是花了一段时间.感觉还是非常有记录的意义呢~~~么么哒*—* 今 ...

  6. Win10 收件箱添加QQ邮箱(2019年5月19日)

    Emmm弄的时候没截图,就语言描述吧,非常简单. 登录到网页端QQ邮箱.点我登录 登录之后,界面上端的Logo右边有个"设置"(字有点小).点它 邮箱设置下面有一堆标签,点击&qu ...

  7. android 访问SMS短信收件箱

    访问 SMS收件箱是另一个常见的需求.首先,需要将读取 SMS 的权限   <uses-permission android:name="android.permission.READ ...

  8. AKKA Inbox收件箱

    起因 得到ActorRef就可以给actor发送消息,但无法接收多回复,也不知道actor是否停止 Inbox收件箱出现就是解决这两个问题 示例 package akka.demo.actor imp ...

  9. JavaMail读取收件箱退信邮件&sol;分析邮件附件获取Message&lowbar;Id

    需求描述:公司最近有个项目邮件通知功能,但是客户上传的邮件地址并不一定存在,以及其他的各种问题.所有希望发送通知后有个回执,及时发现地址存在问题的邮箱. 需求分析:经过分析JavaMail可以读取收件 ...

随机推荐

  1. Android中View的事件分发机制

    简介 事件也称MotionEvent,事件分发机制就是对MotionEvent事件的分发过程,即当一个MotionEvent发生之后,系统需要把这个事件传递给一个具体的View. 点击事件的分发过程由 ...

  2. JS备忘录

    /** *删除数组指定下标或指定对象 */ Array.prototype.remove = function (obj) { for (var i = 0; i < this.length; ...

  3. Binary Indexed Tree 2D 分类: ACM TYPE 2014-09-01 08&colon;40 95人阅读 评论&lpar;0&rpar; 收藏

    #include <cstdio> #include <cstdlib> #include <climits> #include <cstring> # ...

  4. &ast;&ast;RESTful API版本控制策略

    做RESTful开放平台,一方面其API变动越少, 对API调用者越有利:另一方面,没有人可以预测未来,系统在发展的过程中,不可避免的需要添加新的资源,或者修改现有资源.因此,改动升级必不可少,但是, ...

  5. Global&colon;&colon;pickClassMethod&lowbar;DNT

    /*************************************************** Created Date: 19 Jul 2013 Created By: Jimmy Xie ...

  6. poj 1659 Frogs&&num;39&semi; Neighborhood (DFS)

    http://poj.org/problem?id=1659 Frogs' Neighborhood Time Limit: 5000MS   Memory Limit: 10000K Total S ...

  7. Java语言实现简单FTP软件------&gt&semi;FTP软件本地窗口的实现(五)

    1.首先看一下本地窗口的布局效果 2.看一下本地窗口实现的代码框架 2.本地窗口的具体实现代码LocalPanel.java package com.oyp.ftp.panel.local; impo ...

  8. cs代码实现控件移动TranslateTransform

    xaml: <Rectangle> <Rectangle.RenderTransform> <TranslateTransform x:Name="myTran ...

  9. &lbrack;LeetCode&rsqb; Repeated String Match 重复字符串匹配

    Given two strings A and B, find the minimum number of times A has to be repeated such that B is a su ...

  10. Confluence 6 MySQL 测试你的数据库连接

    在你的数据库设置界面,有一个 测试连接(Test connection)按钮可以检查: Confluence 可以连接你的数据库服务器 数据库字符集,隔离级别和存储引擎是正确的 你的数据库用户有正确的 ...