摘要: 微软动态CRM专家罗勇 ,回复303或者20190213可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!我的网站是 www.luoyong.me 。

当然,首先要确认 【设置】> 【电子邮件配置】 > 【电子邮件配置设置】中的 【允许在尚有未解析的电子邮件收件人的情况下发送邮件】设置为是,还有就是连接CRM使用的用户邮箱已经配置好,外发邮件已经测试通了,可以发邮件。

 

不多说了,上代码:

using Microsoft.Crm.Sdk.Messages;using Microsoft.Xrm.Sdk;using Microsoft.Xrm.Sdk.Client;using Microsoft.Xrm.Sdk.Messages;using Microsoft.Xrm.Sdk.Metadata;using System;using System.Collections.Generic;using System.Configuration;using System.Net;using System.ServiceModel.Description;namespace SendEmailToEmailAddrs{    class Program    {        static void Main(string[] args)        {            try            {                string inputKey;                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;                IServiceManagement<IOrganizationService> orgServiceMgr = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(ConfigurationManager.AppSettings["orgUrl"]));                AuthenticationCredentials orgAuCredentials = new AuthenticationCredentials();                orgAuCredentials.ClientCredentials.UserName.UserName = ConfigurationManager.AppSettings["userName"];                orgAuCredentials.ClientCredentials.UserName.Password = ConfigurationManager.AppSettings["passWord"];                string needConfirm = ConfigurationManager.AppSettings["needConfirm"];                using (var orgSvc = GetProxy<IOrganizationService, OrganizationServiceProxy>(orgServiceMgr, orgAuCredentials))                {                    WhoAmIRequest whoReq = new WhoAmIRequest();                    var whoRsp = orgSvc.Execute(whoReq) as WhoAmIResponse;                    var userEntity = orgSvc.Retrieve("systemuser", whoRsp.UserId, new Microsoft.Xrm.Sdk.Query.ColumnSet("fullname"));                    Console.WriteLine(string.Format("欢迎【{0}】登陆到【{1}】", userEntity.GetAttributeValue<string>("fullname"), ConfigurationManager.AppSettings["orgUrl"]));                    Console.WriteLine("本程序用于向指定邮箱发送邮件!");                    if (needConfirm == "Y")                    {                        Console.WriteLine("当前处于需要确认才会继续的模式,若要继续请输入Y然后回车确认!");                        inputKey = Console.ReadLine();                        if (inputKey.ToUpper() == "Y")                        {                            RetrieveAlternateKeys(orgSvc,whoRsp.UserId);                        }                        else                        {                            Console.WriteLine("你选择了取消运行!");                        }                    }                    else                    {                        RetrieveAlternateKeys(orgSvc,whoRsp.UserId);                    }                }                Console.Write("程序运行完成,按任意键退出." + DateTime.Now.ToString());                Console.ReadLine();            }            catch (Exception ex)            {                Console.WriteLine("程序运行出错:" + ex.Message + ex.StackTrace);                Console.ReadLine();            }        }        private static void RetrieveAlternateKeys(OrganizationServiceProxy orgSvc,Guid userId)        {            const string functionName = "用于向指定邮箱发送邮件";            var EmailAddrs = ConfigurationManager.AppSettings["EmailAddrs"];            if (string.IsNullOrEmpty(EmailAddrs))            {                Console.WriteLine("收件邮箱列表为空!");                return;            }            Console.WriteLine(string.Format("开始 {0} - {1}", functionName, DateTime.Now.ToString()));            try            {                Entity emailEntity = new Entity("email");                var newtoPartyList = new List<Entity>();                var fromEntity = new Entity("activityparty");                fromEntity["partyid"] = new EntityReference("systemuser", userId);                emailEntity["from"] = new Entity[] { fromEntity };                foreach (var item in EmailAddrs.Split(';'))                {                    var toEntity = new Entity("activityparty");                    toEntity["paricipationtypemask"] = new OptionSetValue(2);                    toEntity["addressused"] = item;                    newtoPartyList.Add(toEntity);                }                emailEntity["to"] = newtoPartyList.ToArray();                emailEntity["subject"] = ConfigurationManager.AppSettings["subject"];                emailEntity["description"] = ConfigurationManager.AppSettings["description"];                //emailEntity["regardingobjectid"] = new EntityReference("systemuser", userid);                Guid emailGuid = orgSvc.Create(emailEntity);                Console.WriteLine(string.Format("创建的邮件ID是{0}", emailGuid));                SendEmailRequest sendEmailRequest = new SendEmailRequest                {                    EmailId = emailGuid,                    TrackingToken = string.Empty,                    IssueSend = true                };                orgSvc.Execute(sendEmailRequest);                Console.WriteLine("执行发送邮件消息成功!");            }            catch (Exception ex)            {                Console.WriteLine(string.Format("运行 {0} 出现异常:{1}", functionName, ex.Message + ex.StackTrace));            }            Console.WriteLine(string.Format("结束 {0} - {1}", functionName, DateTime.Now.ToString()));            Console.WriteLine("================================================");        }        private static TProxy GetProxy<TService, TProxy>(IServiceManagement<TService> serviceManagement,AuthenticationCredentials authCredentials)            where TService : class            where TProxy : ServiceProxy<TService>        {            Type classType = typeof(TProxy);            if (serviceManagement.AuthenticationType !=                AuthenticationProviderType.ActiveDirectory)            {                AuthenticationCredentials tokenCredentials =                    serviceManagement.Authenticate(authCredentials);                return (TProxy)classType                    .GetConstructor(new Type[] { typeof(IServiceManagement<TService>), typeof(SecurityTokenResponse) })                    .Invoke(new object[] { serviceManagement, tokenCredentials.SecurityTokenResponse });            }            return (TProxy)classType                .GetConstructor(new Type[] { typeof(IServiceManagement<TService>), typeof(ClientCredentials) })                .Invoke(new object[] { serviceManagement, authCredentials.ClientCredentials });        }    }}

 


©著作权归作者所有:来自51CTO博客作者luoyong0201的原创作品,如需转载,请注明出处,否则将追究法律责任

每一份赞赏源于懂得

赞赏

0人进行了赞赏支持

更多相关文章

  1. 自定义工作流活动运行产生System.Security.SecurityException
  2. 表单设计学习
  3. 项目练习总结
  4. 统住UOS系统更新后软件运行异常,回退系统
  5. Java如何实现跨平台?原理是怎样的?
  6. 如何在苹果Mac上的“邮件”中导入或导出邮箱?
  7. “天池PAI-DSW”创建一个斐波那契数列计算函数
  8. 1819、shell脚本基础-bash变量和逻辑运行0脚本编程基础及配置文
  9. Unexpected token '...'. Expected a property name解决

随机推荐

  1. CCNP(ISCW)实验:用命令行配置GRE OVER IPS
  2. Java 类的静态变量存放在哪块内存中?
  3. 那些垃圾收集器,及特点
  4. 解 23 道 MyBatis 题(2)
  5. HotSpot VM 中对象的内存分析
  6. 刷完 557 道 Java 面试题的一些感触
  7. 解 30 道 MyBatis 面试题(3)
  8. 开启 GC 日志
  9. 2: Zabbix5.0使用钉钉机器人报警
  10. 内存溢出复现(OutOfMemory)