Beispiel #1
0
        /// <summary>
        /// Seeds DB with dummy email addresses
        /// </summary>
        public void SeedEmailAddresses()
        {
            var emailAddresses = new List <EmailAddress>()
            {
                new EmailAddress()
                {
                    Id    = 1,
                    Name  = "Michael C",
                    Email = "*****@*****.**"
                },
                new EmailAddress()
                {
                    Id    = 2,
                    Name  = "Jim Garner",
                    Email = "*****@*****.**"
                },
                new EmailAddress()
                {
                    Id    = 3,
                    Name  = "Timothy Smith",
                    Email = "*****@*****.**"
                },
                new EmailAddress()
                {
                    Id    = 4,
                    Name  = "Sara B",
                    Email = "*****@*****.**"
                }
            };

            _context.EmailAddresses.AddRange(emailAddresses);
            _context.SaveChanges();
        }
        public ActionResult Create([Bind(Include = "ID,Name,Email")] FromEmail fromEmail)
        {
            if (ModelState.IsValid)
            {
                db.FromEmails.Add(fromEmail);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(fromEmail));
        }
        public ActionResult Create([Bind(Include = "Id,Name,Roles")] User user)
        {
            user.Roles = Request.Form["Roles"];
            if (ModelState.IsValid)
            {
                db.Users.Add(user);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(user));
        }
        public async Task <IActionResult> Send(Email email, [FromServices] EmailService service, int id)
        {
            var sharedUser = _db.Users.Where(u => u.Email == email.To).FirstOrDefault();

            if (sharedUser != null)
            {
                var user    = _db.Users.Where(u => u.Id == HttpContext.Session.GetString("userId")).FirstOrDefault();
                var message = $"{user.Email} share task with you";

                await service.SendMailAsync(email.To, "SHARE", message);

                ViewBag.Message = "Mail Has Been Sent Successfully";

                UserTask task = _db.Tasks.Where(x => x.Id == id).FirstOrDefault();

                if (task != null)
                {
                    _db.Shares.Add(new UserTaskRelation()
                    {
                        AppUserId  = sharedUser.Id,
                        UserTaskId = task.Id
                    });
                    _db.SaveChanges();
                }

                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                ModelState.AddModelError("", "This email adress is not exists");
            }
            return(View());
        }
        public EmailResponseDto <EmailHistoryTable> AddEmailHistory(EmailHistoryTable historyInput)
        {
            var response = new EmailResponseDto <EmailHistoryTable>();

            try
            {
                historyInput.ID = Guid.NewGuid().ToString();
                historyInput    = _context.EmailHistories.Add(historyInput).Entity;
                if (_context.SaveChanges() == 1)
                {
                    response.Status  = true;
                    response.Message = "Added";
                    response.Result  = historyInput;
                }
                else
                {
                    response.Status  = false;
                    response.Message = "Not Added";
                    response.Result  = historyInput;
                }
                return(response);
            }
            catch (Exception ex)
            {
                response.Status  = false;
                response.Message = ex.Message;
                return(response);
            }
        }
Beispiel #6
0
 public void Update()
 {
     using (EmailDbContext db = new EmailDbContext())
     {
         Email email = db.Emails.Where(x => x.U_Id == userid && x.Eml_Id == emailid).FirstOrDefault();
         try
         {
             if (firstname != email.F_Name)
             {
                 email.F_Name = firstname;
             }
             else if (lastname != email.L_Name)
             {
                 email.L_Name = lastname;
             }
             else if (emailaddress != "")
             {
                 email.Email_Add = emailaddress;
             }
             db.SaveChanges();
             ProecessSuccess?.Invoke(null, null);
         }
         catch (Exception ex)
         {
             ProcessFailDelegate Failed = ProcessFail;
             Failed?.Invoke("Failed" + Environment.NewLine + ex.ToString());
         }
     }
 }
 public ActionResult Create([Bind(Include = "ID,Name,Html,CreatedBy,FromEmail,Receiver,Subject")] Template template)
 {
     if (ModelState.IsValid)
     {
         template.CreatedBy = System.Web.HttpContext.Current.User.Identity.Name.ToString();
         template.Created   = DateTime.Now;
         db.Templates.Add(template);
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     else
     {
         var errors = ModelState.Where(x => x.Value.Errors.Any())
                      .Select(x => new { x.Key, x.Value.Errors });
     }
     return(View(template));
 }
        public ActionResult Create([Bind(Include = "Id,FromEmail,Receiver,ReadReceiptTo,Subject,Body,Created,CreatedBy,Sent")] BroadcastingEmail broadcastingEmail)
        {
            if (ModelState.IsValid)
            {
                broadcastingEmail.Body      = HttpUtility.HtmlDecode(broadcastingEmail.Body);
                broadcastingEmail.Created   = DateTime.Now;
                broadcastingEmail.CreatedBy = System.Web.HttpContext.Current.User.Identity.Name.ToString();
                broadcastingEmail.Sent      = true;
                db.BroadcastingEmails.Add(broadcastingEmail);
                db.SaveChanges();
                SendEmail(broadcastingEmail);
                return(RedirectToAction("SentEmails"));
            }
            else
            {
                var errors = ModelState.Where(x => x.Value.Errors.Any())
                             .Select(x => new { x.Key, x.Value.Errors });

                var sender = db.FromEmails.ToList();
                ViewBag.Senders = sender;

                var receiver = db.ToEmails.ToList();
                ViewBag.ToEmail = receiver;
            }

            return(View("SentEmails", broadcastingEmail));
        }
Beispiel #9
0
        public EmailResponseDto <EmailTemplateTable> AddEmailTemplate(EmailTemplateTable templateInput)
        {
            var response = new EmailResponseDto <EmailTemplateTable>();

            try
            {
                var template = _context.EmailTemplates.FirstOrDefault(st => st.Name.ToLower().Equals(templateInput.Name.ToLower()) &&
                                                                      st.EmailPoolID.Equals(templateInput.EmailPoolID) && (string.IsNullOrEmpty(templateInput.Variant) ||
                                                                                                                           st.Variant.ToLower().Equals(templateInput.Variant.ToLower())));
                if (template != null)
                {
                    response.Status  = false;
                    response.Message = $"This template is already used.";
                    response.Result  = templateInput;
                }
                else
                {
                    templateInput.ID = Guid.NewGuid().ToString();
                    _context.EmailTemplates.Add(templateInput);
                    if (_context.SaveChanges() == 1)
                    {
                        response.Status  = true;
                        response.Message = "Added";
                        response.Result  = templateInput;
                    }
                    else
                    {
                        response.Status  = false;
                        response.Message = "Not Added";
                        response.Result  = templateInput;
                    }
                }

                return(response);
            }
            catch (Exception ex)
            {
                response.Status  = false;
                response.Message = ex.Message;
                return(response);
            }
        }
        public EmailResponseDto <EmailChannelTable> AddEmailChannel(EmailChannelTable channelInput)
        {
            var response = new EmailResponseDto <EmailChannelTable>();

            try
            {
                var channel = _context.EmailChannels.FirstOrDefault(sp => sp.Key.Equals(channelInput.Key) && sp.EmailPoolID.Equals(channelInput.EmailPoolID));
                if (channel != null)
                {
                    response.Status  = false;
                    response.Message = "This Channel already exists.";
                    response.Result  = channelInput;
                }
                else
                {
                    channelInput.ID = Guid.NewGuid().ToString();
                    _context.EmailChannels.Add(channelInput);
                    if (_context.SaveChanges() == 1)
                    {
                        response.Status  = true;
                        response.Message = "Added";
                        response.Result  = channelInput;
                    }
                    else
                    {
                        response.Status  = false;
                        response.Message = "Not Added";
                        response.Result  = channelInput;
                    }
                }

                return(response);
            }
            catch (Exception ex)
            {
                response.Status  = false;
                response.Message = ex.Message;
                return(response);
            }
        }
        public EmailResponseDto <EmailProviderSettingsTable> AddEmailProvider(EmailProviderSettingsTable providerInput)
        {
            var response = new EmailResponseDto <EmailProviderSettingsTable>();

            try
            {
                var provider = _context.EmailProviders.FirstOrDefault(sp => sp.Name.Equals(providerInput.Name) && sp.EmailPoolID.Equals(providerInput.EmailPoolID) && sp.Type.Equals(providerInput.Type));
                if (provider != null)
                {
                    response.Status  = false;
                    response.Message = "The Provider already exists.";
                    return(response);
                }
                else
                {
                    providerInput.ID = Guid.NewGuid().ToString();
                    _context.EmailProviders.Add(providerInput);
                    if (_context.SaveChanges() == 1)
                    {
                        response.Status  = true;
                        response.Message = "Added";
                        response.Result  = providerInput;
                    }
                    else
                    {
                        response.Status  = false;
                        response.Message = "Not Added";
                        response.Result  = providerInput;
                    }
                }
                return(response);
            }
            catch (Exception ex)
            {
                response.Status  = false;
                response.Message = ex.Message;
                return(response);
            }
        }
Beispiel #12
0
        public EmailResponseDto <EmailPoolTable> AddEmailPool(EmailPoolTable emailPoolInput)
        {
            var response = new EmailResponseDto <EmailPoolTable>();

            try
            {
                var isPoolExist = _context.EmailPools.Any(sp => sp.Name.ToLower().Equals(emailPoolInput.Name.ToLower()));
                if (!isPoolExist)
                {
                    emailPoolInput.ID = Guid.NewGuid().ToString();
                    _context.EmailPools.Add(emailPoolInput);
                    if (_context.SaveChanges() == 1)
                    {
                        response.Status  = true;
                        response.Message = "Added";
                        response.Result  = emailPoolInput;
                    }
                    else
                    {
                        response.Status  = false;
                        response.Message = "Not Added";
                        response.Result  = emailPoolInput;
                    }
                }
                else
                {
                    response.Status  = false;
                    response.Message = "Email pool already exists";
                    response.Result  = emailPoolInput;
                }
                return(response);
            }
            catch (Exception ex)
            {
                response.Status  = false;
                response.Message = ex.Message;
                return(response);
            }
        }
Beispiel #13
0
        public void SendEmail(MailMessage emailMessage, int id)
        {
            try
            {
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;

                smtp.Credentials = new NetworkCredential("*****@*****.**", "*******");
                smtp.EnableSsl   = true;
                smtp.Send(emailMessage);

                EmailData updateEmail = new EmailData();
                updateEmail = _context.EmailDatas.FirstOrDefault(c => c.Id == id);

                if (updateEmail.StatusId == 1)
                {
                    updateEmail.StatusId  = 2;
                    updateEmail.CommCount = 1;
                    _context.SaveChanges();
                }
                else if (updateEmail.StatusId == 2)
                {
                    updateEmail.CommCount++;
                    _context.SaveChanges();
                }
                else if (updateEmail.StatusId == 3)
                {
                    updateEmail.StatusId = 4;
                    _context.SaveChanges();
                }
            }
            catch (Exception e)
            {
            }
        }
Beispiel #14
0
        public void GetItems_ReturnsSingleItem()
        {
            var builder = new DbContextOptionsBuilder <EmailDbContext>();

            builder.UseInMemoryDatabase <EmailDbContext>(Guid.NewGuid().ToString());
            var options = builder.Options;

            using (var context = new EmailDbContext(options))
            {
                var orders = new List <Email>
                {
                    new Email {
                        Id = 33, Subject = "Email Subject"
                    },
                };

                context.Emails.AddRange(orders);
                context.SaveChanges();
            }

            using (var context = new EmailDbContext(options))
            {
                var loggerMock   = new Mock <ILogger <EmailController> >();
                var config       = new MapperConfiguration(cfg => cfg.AddProfile <AutoMapping>());
                var mapper       = config.CreateMapper();
                var settingsMock = new Mock <IOptions <AppSettings> >();
                var controller   = new EmailController(loggerMock.Object, mapper, context, settingsMock.Object);
                var result       = controller.Get();

                var okResult = result as OkObjectResult;

                // assert
                Assert.NotNull(okResult);
                Assert.True(okResult is OkObjectResult);
                Assert.IsType <List <EmailDTO> >(okResult.Value);

                Assert.Equal(StatusCodes.Status200OK, okResult.StatusCode);
                var collection = okResult.Value as List <EmailDTO>;
                Assert.Single(collection);
            }
        }
        public EmailResponseDto <EmailQuotaTable> UpdateEmailQuota(string channelID)
        {
            var response = new EmailResponseDto <EmailQuotaTable>();

            try
            {
                var emailQuota = _context.EmailQuotas.FirstOrDefault(q => q.EmailChannelID == channelID);
                if (emailQuota != null)
                {
                    var countInt = Convert.ToInt32(emailQuota.TotalConsumption); // TODO Implement encryption
                    countInt += 1;
                    emailQuota.TotalConsumption = countInt;
                    _context.EmailQuotas.Update(emailQuota);
                }
                else
                {
                    emailQuota = new EmailQuotaTable()
                    {
                        EmailChannelID     = channelID,
                        MonthlyQuota       = 100,
                        MonthlyConsumption = 1,
                        TotalConsumption   = 1
                    };
                    _context.EmailQuotas.Add(emailQuota);
                }
                if (_context.SaveChanges() == 1)
                {
                    response.Status  = true;
                    response.Message = "Email Quota is updated";
                    response.Result  = emailQuota;
                }
                return(response);
            }
            catch (Exception ex)
            {
                response.Status  = false;
                response.Message = ex.Message;
                return(response);
            }
        }
Beispiel #16
0
        public async Task <string> FunctionHandler(SNSEvent snsEvent, ILambdaContext context)
        {
            string   mongoConnectionString = Environment.GetEnvironmentVariable("MongoDB_ConnectionString");
            DateTime now = DateTime.UtcNow;

            XmlConfigurator.Configure(m_logRepo, new System.IO.FileInfo("log4net.config"));
            foreach (var record in snsEvent.Records)
            {
                var     snsRecord = record.Sns;
                JObject message   = JObject.Parse(snsRecord.Message);
                string  notificationId;

                switch (message["notificationType"].ToString())
                {
                case "Bounce":
                    notificationId = message["bounce"]["feedbackId"].ToString();
                    break;

                case "Complaint":
                    notificationId = message["complaint"]["feedbackId"].ToString();
                    break;

                default:
                    notificationId = "";
                    break;
                }

                m_log.Info($"[{record.EventSource} {snsRecord.Timestamp}] Message = {snsRecord.Message}");
                if (!String.IsNullOrEmpty(mongoConnectionString))
                {
                    string         mongoDatabaseName = mongoConnectionString.Substring(mongoConnectionString.LastIndexOf("/") + 1);
                    MongoClient    mongoClient       = new MongoClient(mongoConnectionString);
                    IMongoDatabase mongoDatabase     = mongoClient.GetDatabase(mongoDatabaseName);
                    IMongoCollection <EmailNotificationLog> emailNotificationLogCollection = mongoDatabase.GetCollection <EmailNotificationLog>("EmailNotificationLog");
                    IMongoCollection <EmailBlackList>       emailBlackListCollection       = mongoDatabase.GetCollection <EmailBlackList>("EmailBlackList");

                    emailBlackListCollection.Indexes.CreateOne(new BsonDocument("EmailAddress", 1), new CreateIndexOptions {
                        Name = "UX_EmailBlackList_EmailAddress", Unique = true
                    });
                    await emailNotificationLogCollection.InsertOneAsync(new EmailNotificationLog {
                        NotificationType = message["notificationType"].ToString(),
                        NotificationId   = notificationId,
                        Event            = BsonSerializer.Deserialize <BsonDocument>(snsRecord.Message),
                        Timestamp        = snsRecord.Timestamp,
                        Created          = now
                    });

                    if ((message["notificationType"].ToString() == "Bounce") && (message["bounce"]["bounceType"].ToString() == "Permanent"))
                    {
                        foreach (JObject bouncedRecipient in message["bounce"]["bouncedRecipients"])
                        {
                            string emailAddress = bouncedRecipient["emailAddress"].ToString().ToLower();
                            long   count        = await emailBlackListCollection.Find(Builders <EmailBlackList> .Filter.Where(x => x.EmailAddress == emailAddress)).CountAsync();

                            if (count == 0)
                            {
                                await emailBlackListCollection.InsertOneAsync(new EmailBlackList {
                                    EmailAddress = emailAddress,
                                    Created      = now
                                });
                            }
                        }
                    }
                }
                if (EmailDbContext.IsActive())
                {
                    using (var db = new EmailDbContext()) {
                        var emailNotificationLog = new EmailNotificationLog {
                            NotificationType = message["notificationType"].ToString(),
                            NotificationId   = notificationId,
                            Message          = snsRecord.Message,
                            Timestamp        = snsRecord.Timestamp,
                            Created          = now
                        };

                        db.EmailNotificationLog.Add(emailNotificationLog);
                        if ((message["notificationType"].ToString() == "Bounce") && (message["bounce"]["bounceType"].ToString() == "Permanent"))
                        {
                            foreach (JObject bouncedRecipient in message["bounce"]["bouncedRecipients"])
                            {
                                string emailAddress = bouncedRecipient["emailAddress"].ToString().ToLower();

                                if (db.EmailBlackList.Where(x => x.EmailAddress == emailAddress).Count() == 0)
                                {
                                    var emailBlackList = new EmailBlackList {
                                        EmailAddress = emailAddress,
                                        Created      = now
                                    };

                                    db.EmailBlackList.Add(emailBlackList);
                                }
                            }
                        }
                        db.SaveChanges();
                    }
                }
            }
            return("okay");
        }
Beispiel #17
0
 /// <summary>
 /// Saves any updates made to the database context
 /// </summary>
 /// <returns></returns>
 public bool Save()
 {
     // Retuns the number of state entries written to the database.
     return(_context.SaveChanges() >= 0);
 }
Beispiel #18
0
 public void UpdateLoginTime(AccountUser user)
 {
     user.LoginTime = DateTime.Now;
     _db.Entry <AccountUser>(user).State = System.Data.Entity.EntityState.Modified;
     _db.SaveChanges();
 }
Beispiel #19
0
        public static void Send(MailMessage message)
        {
            // Queue an e-mail to send later
            using (EmailDbContext db = new EmailDbContext())
            {
                try
                {
                    EmailMessage emailMessage = new EmailMessage
                    {
                        Id         = Guid.NewGuid(),
                        From       = ((message.From == null) ? (new MailAddress("*****@*****.**", "Doug Lockwood's Application")).ToString() : message.From.ToString()),
                        To         = message.To.ToString(),
                        Cc         = message.CC.ToString(),
                        Bcc        = message.Bcc.ToString(),
                        Subject    = message.Subject,
                        Body       = message.Body,
                        IsBodyHtml = message.IsBodyHtml,
                        ReplyTo    = message.ReplyToList.ToString(),
                        Created    = DateTime.Now,
                        Expires    = DateTime.Now.AddDays(_daysToExpiration)
                    };

                    db.Email.Add(emailMessage);
                    db.SaveChanges();
                }
                catch
                {
                    throw;
                }
            }
            ////// Send an e-mail
            ////SmtpClient client = new SmtpClient
            ////{
            ////    Host = "host276.hostmonster.com",
            ////    Credentials = new NetworkCredential("*****@*****.**", "D0ugl@$L"),
            ////};

            ////message.From = new MailAddress("*****@*****.**");

            ////if (message.IsBodyHtml)
            ////{
            ////    message.Body = message.Body.Replace(@"\r\n", "<br/>");
            ////}

            ////message.Body +=
            ////    ((message.IsBodyHtml) ? "<p>&nbsp;</p><hr/><footer><p>" : "\r\n\r\n--------------------\r\n")
            ////    + "This message was sent by McREL International through an unmonitored e-mail address. Please do not reply to this e-mail."
            ////    + ((message.IsBodyHtml) ? "</p><p>" : "\r\n\r\n")
            ////    + "You can learn more about McREL International by visiting us "
            ////    + ((message.IsBodyHtml) ? "<a href=\"http://www.mcrel.org\">online</a>.</p><p>" : "online at http://www.mcrel.org.\r\n\r\n")
            ////    + "McREL International"
            ////    + ((message.IsBodyHtml) ? "<br/>" : "\r\n")
            ////    + "4601 DTC Boulevard, Suite 500"
            ////    + ((message.IsBodyHtml) ? "<br/>" : "\r\n")
            ////    + "Denver, CO 80237-2596"
            ////    + ((message.IsBodyHtml) ? "<br/>" : "\r\n")
            ////    + "P: 303.337.0990"
            ////    + ((message.IsBodyHtml) ? "<br/>" : "\r\n")
            ////    + "F: 303.337.3005"
            ////    + ((message.IsBodyHtml) ? "<br/>" : "\r\n")
            ////    + "*****@*****.**"
            ////    + ((message.IsBodyHtml) ? "<br/>" : "\r\n")
            ////    + ((message.IsBodyHtml) ? "<a href=\"http://www.mcrel.org\">www.mcrel.org</a>" : "http://www.mcrel.org")
            ////    + ((message.IsBodyHtml) ? "</p></footer>" : "\r\n--------------------\r\n")
            ////    ;


            ////client.Send(message);
        }