Esempio n. 1
0
        private void CacheTemplates()
        {
            lock (typeof(ElasticMailPushService))
            {
                if (!_cached)
                {
                    var mailModelType = typeof(MailModel);

                    //find all email models in the application
                    mailModelType.Assembly
                    .GetTypes()
                    .Where(_type => _type.Namespace == mailModelType.Namespace)
                    .Where(_type => _type != mailModelType)
                    .ForAll((_cnt, _type) =>
                    {
                        //compile and cache the mail models
                        var templateSource = new MailModelTemplateSource(_type);
                        var key            = new NameOnlyTemplateKey(templateSource.Name, ResolveType.Global, null);

                        if (!Engine.Razor.IsTemplateCached(key, _type))
                        {
                            Engine.Razor.Compile(templateSource, templateSource.Name, _type);
                        }
                    });
                    _cached = true;
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Send the Email
        /// </summary>
        /// <param name="model">Mail to Send</param>
        /// <returns>Operation</returns>
        public Operation SendMail(MailModel model)
        => Operation.Try(() =>
        {
            CacheTemplates();

            var modelType = model.GetType();
            var mail      = new ElasticemailMessage
            {
                From       = new MailAddress(model.From),
                Subject    = model.Subject.ThrowIfNull("invalid mail subject"),
                IsBodyHtml = true,
                Body       = Engine.Razor.Run(MailModelTemplateSource.TemplateName(modelType), modelType, model),
            };
            model.Recipients.ForAll((_cnt, _r) => mail.To.Add(new MailAddress(_r)));

            new ElasticemailWebApi(_apikey)
            .Send(mail)
            .ThrowIf(_r => _r.ResultType == ResultType.Error, _r => new Exception(_r.ErrorMessage));
        });