コード例 #1
0
 public ViewResult Index(MailModel _objModelMail)
 {
     if (ModelState.IsValid)
     {
         MailMessage mail = new MailMessage();
         mail.To.Add(_objModelMail.to);
         mail.From = new MailAddress(_objModelMail.from);
         mail.Subject = _objModelMail.Subject;
         string Body = _objModelMail.Body;
         mail.Body = Body;
         mail.IsBodyHtml = true;
         SmtpClient smtp = new SmtpClient();
         smtp.Host = "smtp.gmail.com";
         smtp.Port = 587;
         smtp.UseDefaultCredentials = false;
         smtp.Credentials = new System.Net.NetworkCredential
         ("username", "password");// Enter seders User name and password
         smtp.EnableSsl = true;
         smtp.Send(mail);
         return View("Index", _objModelMail);
     }
     else
     {
         return View();
     }
 }
コード例 #2
0
        private static void NewMail(SendMailRequest request)
        {
            try
            {
                var model = new MailModel
                {
                    Content = request.Content,
                    Sender = request.Sender,
                    SentAt = request.SentAt.ToString("HH:mm.ss"),
                    SentDate = request.SentAt
                };

                MailBag.Add(model);
                _Clients.All.newMail(model);

                _Queue.Reply<MailBroadcastEvent>(new MailBroadcastEvent
                {
                    Sender = request.Sender,
                    SentAt = request.SentAt,
                    BroadcastAt = DateTime.Now
                });
            }
            catch
            {
                _Queue.Reply<HandlerFailedEvent>(new HandlerFailedEvent
                {
                    Sender = request.Sender,
                    SentAt = request.SentAt,
                    Message = "Broadcast failed!"
                });
            }
        }
コード例 #3
0
        public ActionResult Index(string user)
        {
            var model = new MailModel
            {
                Sender = user
            };

            return View(model);
        }
コード例 #4
0
        private void EnviarMail(TicketModel ticketModel)
        {
            ConsultarDatosCorreoModel consultarDatosCorreoModel = iSeguimientoTicketsDataAccess.ObtenerDatosCorreo(ticketModel.TicketId);
            string bodyMail = BodyMail(ticketModel);

            MailModel mailModel = new MailModel
            {
                Body    = bodyMail,
                Subject = ticketModel.Tipo + " - " + ticketModel.TicketId
            };

            if (!string.IsNullOrEmpty(ticketModel.MailResponsable))
            {
                List <string> mailsCcs = new List <string>();
                List <string> mailsTo  = new List <string>
                {
                    ticketModel.MailResponsable
                };

                mailModel.MailsTo = mailsTo;

                if (!string.IsNullOrEmpty(ticketModel.CopiarA))
                {
                    String[] correos = ticketModel.CopiarA.Split(';');
                    foreach (var copiarA in correos)
                    {
                        if (!string.IsNullOrEmpty(copiarA))
                        {
                            mailsCcs.Add(copiarA);
                        }
                    }
                }
                mailsCcs.Add(consultarDatosCorreoModel.MailLevanto);
                mailsCcs.Add(consultarDatosCorreoModel.MailReporta);
                mailModel.MailsCc = mailsCcs;
                List <string> attachementsPathsFiles = new List <string>();
                foreach (var archivo in ticketModel.Archivos)
                {
                    attachementsPathsFiles.Add(archivo.RutaArchivo + archivo.NombreArchivo);
                    mailModel.AttachmentName = archivo.NombreArchivo;
                }
                mailModel.AttachementsPathsFiles = attachementsPathsFiles;

                SendMailUtil.GetInstance().SendMailTickets(mailModel);
            }
        }
コード例 #5
0
 public ActionResult SendMail()
 {
     if (Session["uname"] != null)
     {
         MailModelService mailModel = new MailModelService();
         MailModel        model     = new MailModel();
         model.To      = Request["to"];
         model.From    = Session["From"].ToString();
         model.Subject = Request["subject"];
         model.Body    = Request["body"];
         model.Date    = DateTime.Now;
         mailModelService.InsertMail(model);
         ViewBag.status = "Mail Has been Sent Successfully";
         return(View());
     }
     return(RedirectToAction("Index", "Home"));
 }
コード例 #6
0
        public IHttpActionResult Contact(MailModel mail)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                SendMail("*****@*****.**", "NEW CONTACT FORM MESSAGE", mail);
                return(Ok());
            }
            catch (Exception e)
            {
                return(BadRequest());
            }
        }
コード例 #7
0
    public IActionResult AprobarUsuario(int id)
    {
        Usuario usuarioNuevo = UsuarioDao.getUsuario(_context, id);

        usuarioNuevo.Nombre     = usuarioNuevo.Nombre;
        usuarioNuevo.Apellido   = usuarioNuevo.Apellido;
        usuarioNuevo.Contraseña = usuarioNuevo.Contraseña;
        usuarioNuevo.Mail       = usuarioNuevo.Mail;
        usuarioNuevo.Estado     = Estado.APROBADO;
        UsuarioDao.editarUsuario(_context, usuarioNuevo);
        agregarMensajePrincipal("Usuario aprobado", TipoMensaje.EXITO);
        TempData["Mensajes"] = mensajes;
        MailModel _objModelMail = new MailModel();

        mailService.avisoDeAprobacionAUsuario(_objModelMail, usuarioNuevo);
        return(View("~/Views/Inicio/Inicio.cshtml", new InicioModelAndView()));
    }
        public CMSResult SendDailyPracticePaper(DailyPracticePaperViewModel viewModel)
        {
            var cmsResult = new CMSResult();

            try
            {
                var    projection  = _branchAdminService.GetBranchAdminById(User.Identity.GetUserId());
                var    bodySubject = "Daily Practice Paper Created";
                string body        = string.Empty;
                using (StreamReader reader = new StreamReader(Server.MapPath("~/MailDesign/CommonMailDesign.html")))
                {
                    body = reader.ReadToEnd();
                }
                body = body.Replace("{BranchName}", projection.BranchName);
                body = body.Replace("{ModuleName}", User.Identity.GetUserName() + "<br/>" + "Dily Practice Paper:" + viewModel.Description + "<br/>");
                body = body.Replace("{BranchAdminEmail}", User.Identity.GetUserName());

                var emailMessage = new MailModel
                {
                    IsBranchAdmin = true,
                    Body          = body,
                    Subject       = bodySubject,
                    To            = ConfigurationManager.AppSettings[Common.Constants.AdminEmail]
                };
                var result = _emailService.Send(emailMessage);
                if (result)
                {
                    cmsResult.Results.Add(new Result {
                        Message = "Sent Successfully.", IsSuccessful = true
                    });
                }
                else
                {
                    cmsResult.Results.Add(new Result {
                        Message = "Something went wrong.", IsSuccessful = false
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message + "catch SendDailyPracticePaper");
                throw;
            }

            return(cmsResult);
        }
コード例 #9
0
        public MailModel Create(UserClaimsChangedEvent model)
        {
            //Generate mailModel
            ViewModel viewModel = new ViewModel()
                                  .Add("AccountId", model.AccountId)
                                  .Add("ChangeType", ((int)model.ChangeType).ToString())
                                  .Add("Username", model.Username);

            MailModel mailModel = new MailModel()
                                  .AddFrom(_smtpConfig.Username)
                                  .AddTo(model.Email)
                                  .AddSubject("Changes in your account")
                                  .AddTemplateFile(_templateFile)
                                  .AddViewModel(viewModel);

            return(mailModel);
        }
コード例 #10
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email, PhoneNumber = model.Phone
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    UserViewModel userInfo = new UserViewModel();
                    userInfo.LastName = model.LastName;
                    userInfo.Name     = model.Name;
                    userInfo.Nickname = model.Nickname;
                    userInfo.Phone    = model.Phone;
                    userInfo.UserId   = user.Id;
                    int errorCode = userInfo.Save();
                    if (errorCode == 11)
                    {
                        ModelState.AddModelError("", "Nickname already exists");
                        return(View(model));
                    }
                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var       callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    MailModel mail        = new MailModel();
                    mail.Email   = UserManager.FindById(user.Id).Email;
                    mail.Subject = "Confirm Email";
                    mail.Body    = "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>";
                    mail.SendMail();
                    return(RedirectToAction("Index", "Home"));
                }


                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #11
0
        private Personalization[] ConstructPersonalizationObject(MailModel mailModel)
        {
            var personalizations = new Personalization[1];

            personalizations[0] = new Personalization();

            var toContacts = new List <Contact>();

            foreach (var to in mailModel.To)
            {
                toContacts.Add(new Contact {
                    Email = to
                });
            }

            personalizations[0].To = toContacts.ToArray();

            if (mailModel.Cc?.Count() > 0)
            {
                var ccContacts = new List <Contact>();
                foreach (var cc in mailModel.Cc)
                {
                    ccContacts.Add(new Contact {
                        Email = cc
                    });
                }

                personalizations[0].Cc = ccContacts.ToArray();
            }

            if (mailModel.Bcc?.Count() > 0)
            {
                var bccContacts = new List <Contact>();
                foreach (var bcc in mailModel.Bcc)
                {
                    bccContacts.Add(new Contact {
                        Email = bcc
                    });
                }

                personalizations[0].Bcc = bccContacts.ToArray();
            }

            return(personalizations);
        }
コード例 #12
0
        public async Task <ActionResult <ParticipantsDTO> > AddParticipant(int EventId, int UserId, ParticipantsDTO participantsDto)
        {
            try
            {
                var participant = _mapper.Map <Participants>(participantsDto);
                participant.EventId = EventId;
                participant.UserId  = UserId;

                _participantsRepository.CreateParticipants(participant);

                var eventTemp = await _eventRepository.GetEventByIdAsync(EventId);

                var    mappedEvent = _mapper.Map <EventFullDTO>(eventTemp);
                string eventTitle  = mappedEvent.EventName;

                var hostUser = await _userRepository.GetUserByIdAsync(eventTemp.UserId);

                var    mappedHost = _mapper.Map <UserFullDTO>(hostUser);
                string hostName   = mappedHost.Name;
                string hostEmail  = mappedHost.Email;

                var participantUser = await _userRepository.GetUserByIdAsync(UserId);

                var    mappedParticipant = _mapper.Map <UserFullDTO>(participantUser);
                string participantsName  = mappedParticipant.Name;

                MailModel mailModel = new MailModel();
                mailModel.From    = "*****@*****.**";
                mailModel.To      = participantUser.Email;
                mailModel.Subject = "You have joined the event " + eventTitle;
                mailModel.Body    = "Hi " + participantsName + "\n ! You have joined the event hosted by \n " + hostName + ". Here is the " + hostName + "'s contact email address: " + hostEmail + " We hope you will have fun. Thanks for using our app!";
                _emailService.SendEmail(mailModel);

                if (await _participantsRepository.SaveChangeAsync())
                {
                    return(Ok());
                }
            }
            catch (Exception)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, "Database Failure"));
            }

            return(BadRequest());
        }
コード例 #13
0
        public ActionResult Index(MailModel objModelMail, HttpPostedFileBase fileUploader)
        {
            if (ModelState.IsValid)
            {
                //https://www.google.com/settings/security/lesssecureapps
                //Make Access for less secure apps=true

                string from = "*****@*****.**";
                using (MailMessage mail = new MailMessage(from, objModelMail.To))
                {
                    try
                    {
                        mail.Subject = objModelMail.Subject;
                        mail.Body    = objModelMail.Body;
                        if (fileUploader != null)
                        {
                            string fileName = Path.GetFileName(fileUploader.FileName);
                            mail.Attachments.Add(new Attachment(fileUploader.InputStream, fileName));
                        }
                        mail.IsBodyHtml = false;
                        SmtpClient smtp = new SmtpClient();
                        smtp.Host      = "smtp.gmail.com";
                        smtp.EnableSsl = true;
                        NetworkCredential networkCredential = new NetworkCredential(from, "159753159753p");
                        smtp.UseDefaultCredentials = false;
                        smtp.Credentials           = networkCredential;
                        smtp.Port = 587;
                        smtp.Send(mail);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        ViewBag.Message = "Sent";
                    }
                    return(View("Index", objModelMail));
                }
            }
            else
            {
                return(View());
            }
        }
コード例 #14
0
        public static bool SendGmail(MailModel mailModel)
        {
            var result = true;

            try
            {
                MailMessage mMail = new MailMessage
                {
                    From       = new MailAddress(mailModel.SenderAccount, mailModel.SenderName),
                    Subject    = mailModel.Subject,
                    Body       = mailModel.Body,
                    IsBodyHtml = true
                };
                foreach (var item in mailModel.LstReceiver)
                {
                    mMail.To.Add(item);
                }
                var smtpClient = new SmtpClient
                {
                    Host                  = "smtp.gmail.com",
                    Port                  = 587,
                    EnableSsl             = true,
                    DeliveryMethod        = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials           = new NetworkCredential(mailModel.SenderAccount, mailModel.SenderPassword)
                };
                if (mailModel.LstAttachment != null && mailModel.LstAttachment.Count > 0)
                {
                    foreach (var item in mailModel.LstAttachment)
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            mMail.Attachments.Add(new Attachment(item));
                        }
                    }
                }
                smtpClient.Send(mMail);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                result = false;
            }
            return(result);
        }
コード例 #15
0
        public IActionResult MailCompose(string title, string message, string[] taker)
        {
            MailModel        mailParent  = new MailModel();
            MailDetailsModel mailDetails = new MailDetailsModel();

            if (string.IsNullOrEmpty(taker.ToString()) || string.IsNullOrEmpty(message) || string.IsNullOrEmpty(title))
            {
                UserInfoListele();
                return(Json(new { result = false }));
            }
            else
            {
                var userSenderId = HttpContext.User.Claims.Where(c => c.Type == ClaimTypes.Sid)
                                   .Select(c => c.Value)
                                   .SingleOrDefault();

                mailParent.Title      = title;
                mailParent.Message    = message;
                mailParent.Date       = DateTime.Now;
                mailParent.SenderID   = Guid.Parse(userSenderId);
                mailParent.MailStatus = MailDetailStatus.Silinmedi;
                var mailParentMessageInsert = MailRepo.NewInstance.Do.Insert(mailParent);

                mailDetails.MailParentID     = Guid.Parse(mailParentMessageInsert.ID.ToString());
                mailDetails.UserTakerID      = Guid.Parse(userSenderId);
                mailDetails.SenderStatus     = true;
                mailDetails.mailDetailStatus = MailDetailStatus.Okunmadi;

                var mailDetailsSenderFirstInsert = MailDetailsRepo.NewInstance.Do.Insert(mailDetails);

                mailDetails.MailParentID     = Guid.Parse(mailParentMessageInsert.ID.ToString());
                mailDetails.mailDetailStatus = MailDetailStatus.Okunmadi;
                var mailIDzero = new Guid();

                foreach (var item in taker)
                {
                    mailDetails.UserTakerID  = Guid.Parse(item);
                    mailDetails.SenderStatus = false;
                    var test = MailDetailsRepo.NewInstance.Do.Insert(mailDetails);
                    mailDetails.MailDetailsId = mailIDzero;
                }
                UserInfoListele();
                return(Json(new { result = true }));
            }
        }
コード例 #16
0
        public async void DeleteUserRequest(int id)
        {
            var          model = _context.RegistrationRequests.FirstOrDefault(p => p.Id == id);
            IdentityUser user  = await _userManager.FindByEmailAsync(model.Email);

            await _userManager.DeleteAsync(user);

            _context.RegistrationRequests.Remove(model);
            _context.SaveChanges();

            MailModel mail = new MailModel();

            mail.ToMail.Add(model.Email);
            mail.Subject = "User Deleted";
            mail.Body    = "Your account has been deleted";

            MailSenderService.SendMail(mail);
        }
コード例 #17
0
 public ActionResult Contact([Bind(Include = "From,Subject,Body")] MailModel mail)
 {
     if (ModelState.IsValid)
     {
         try
         {
             string to = "[email protected],[email protected],[email protected],[email protected]";
             Email.Send(to, mail.From, "Feedback", mail.Body, EmailTemplate.Feedback);
             ViewBag.Result = "Success";
             return(RedirectToAction("Index", "Result", new { Message = ResultMessage.FeedbackSend }));
         }
         catch (Exception)
         {
             ViewBag.Result = "Error";
         }
     }
     return(View(mail));
 }
コード例 #18
0
ファイル: MailSender.cs プロジェクト: tlianglstyle/Gaver
        public async Task SendAsync(MailModel mail)
        {
            if (options.SendGridApiKey.IsNullOrEmpty())
            {
                throw new FriendlyException(EventIds.SendGridApiKeyMissing, "Mangler API-nøkkel for SendGrid");
            }
            var sendGridMail = mapper.Map <SendGridMail>(mail);

            try {
                await options.SendGridUrl
                .WithOAuthBearerToken(options.SendGridApiKey)
                .PostJsonAsync(sendGridMail);

                logger.LogInformation("Mail sent to {To}", mail.To);
            } catch (Exception e) {
                logger.LogErrorAndThrow(EventIds.ShareListFailed, e, "Failed to share list");
            }
        }
コード例 #19
0
ファイル: MailController.cs プロジェクト: LiiLunzyT/Web
 public ActionResult SendMail(MailModel model)
 {
     if (!ModelState.IsValid)
     {
         return(View("Index"));
     }
     System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
     mail.From = new System.Net.Mail.MailAddress(model.From);
     mail.To.Add(model.To);
     mail.Subject    = model.Subject;
     mail.Body       = model.Body;
     mail.IsBodyHtml = true;
     System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
     smtp.Credentials = new System.Net.NetworkCredential(model.From, model.Password);
     smtp.EnableSsl   = true;
     smtp.Send(mail);
     return(RedirectToAction("Index"));
 }
コード例 #20
0
        // Create JSON File with
        public string WriteToJsonMailData(MailModel mailModel, IWebHostEnvironment env)
        {
            string mailFileName = $"MailDate.JSON";
            string wwwPath      = env.WebRootPath;
            string filePath     = Path.Combine(wwwPath, "Fisiere");

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            filePath = Path.Combine(filePath, mailFileName).ToString();
            string jsonString = JsonSerializer.Serialize(mailModel, new JsonSerializerOptions {
                WriteIndented = true
            });

            File.WriteAllText(filePath, jsonString);
            return(filePath);
        }
コード例 #21
0
        public HttpResponseMessage Contact(MailModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            if (Request.Headers.Authorization.ToString() != ConfigurationManager.AppSettings["AuthorizationHeader"])
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

            var mailer = new UserMailer();

            mailer.Contact(model).Send();

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
コード例 #22
0
ファイル: MailController.cs プロジェクト: K1ler55/WebPioKa
        public ActionResult Send(MailModel model)
        {
            User user = (User)Session["users"];

            if (user == null)
            {
                return(RedirectToAction("Index", "Login"));
            }
            ModelMail mail = new ModelMail();

            NH.NHibernateOperation operation = new NH.NHibernateOperation();
            User u = operation.GetUserById(model.Id_user);

            mail.from = user.Email;
            mail.to   = u.Email;

            return(View(mail));
        }
コード例 #23
0
        public MailModel GetMailDetail(MailModel request)
        {
            var character = new ESI.Models.Character.Detail()
            {
                Id = request.OwnerId
            };
            var endpoint = _esiRepository.GetByName(Resources.ApplicantEndpointName);

            var token = ESI.SingleSignOn.GetTokensFromRefreshToken(endpoint.ClientId, endpoint.SecretKey,
                                                                   _recruitRepository.GetRefreshTokenForApplicant(request.OwnerId));
            var recode = character.GetMail(request.Id, token.AccessToken).Body.Replace("<br>", "{br}");

            recode       = Regex.Replace(recode, "<.+?>", string.Empty);
            recode       = recode.Replace("{br}", "<br />");
            request.Body = recode;

            return(request);
        }
コード例 #24
0
 /// <summary>
 /// 发送邮件
 /// </summary>
 /// <param name="account">邮箱账户</param>
 /// <param name="mailModel">邮箱类</param>
 /// <returns></returns>
 public void SendMail(MailAccount account, MailModel mailModel)
 {
     try
     {
         MailHelper.Send(account, mailModel);
     }
     catch (Exception ex)
     {
         if (ex is ExceptionEx)
         {
             throw;
         }
         else
         {
             throw ExceptionEx.ThrowBusinessException(ex);
         }
     }
 }
コード例 #25
0
        public async System.Threading.Tasks.Task <ActionResult> Index(MailModel model)
        {
            string content = JsonConvert.SerializeObject(model);

            using (var client = new HttpClient())
            {
                var response = await client.PostAsync(
                    "<keep your url here>",
                    new StringContent(content, Encoding.UTF8, "application/json"));

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    ViewBag.Message = "Email has been sent successfully.";
                }
            }

            return(View());
        }
コード例 #26
0
        public static async Task <bool> SendMail(MailModel mail)
        {
            var stringContent = new StringContent(
                JsonConvert.SerializeObject(mail), Encoding.UTF8, "application/json");
            var response = await ControllerClient.PostAsync(
                ControllerClient.BaseAddress + "sendmail", stringContent);

            var result = await response.Content.ReadAsStringAsync();

            if (result == "true")
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #27
0
        public ActionResult Send(MailModel model)
        {
            setupSession();
            bool bretval = false;

            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];

                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path     = Path.Combine(Server.MapPath("~/FileUploads/Attachements/"), UserSession.LoggedInUserId + fileName);
                    file.SaveAs(path);
                    model.AttachmentSize = (file.ContentLength / 1024).ToString();
                    model.Attachment     = "/FileUploads/Attachements/" + UserSession.LoggedInUserId + fileName;
                }
            }
            model.From   = UserSession.Email;
            model.Status = 1;
            bretval      = MailboxService.Instance.SendMessage(ref model, UserSession);
            bool isInternal = MailboxService.Instance.checkInternal(model.From, model.To);

            if (isInternal == true)
            {
                model.IsInternal = 1;
                model.IsExternal = 0;
            }
            else
            {
                model.IsInternal = 0;
                model.IsExternal = 1;
            }
            model.SenderId   = UserSession.LoggedInUserId;
            model.ReceiverId = MailboxService.Instance.getUserIdByEMail(model.To, UserSession);
            bretval          = MailboxService.Instance.InsertStatistics(model, UserSession);
            if (bretval)
            {
                ViewBag.IsSuccess = true;
                ViewBag.Message   = "Message has been sent succesfully.";
            }
            model = new MailModel();
            return(View("ComposeMail", model));
        }
コード例 #28
0
        public static bool SendMail(MailModel mail)
        {
            SmtpClient smtp = new SmtpClient();

            try
            {
                var configurationFile = WebConfigurationManager.OpenWebConfiguration("~/web.config");
                var mailSettings      = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
                if (Equals(mailSettings, null))
                {
                    Loger.Log("Mail setting not invalid!!");
                    return(false);
                }
                int    port     = mailSettings.Smtp.Network.Port;
                string host     = mailSettings.Smtp.Network.Host;
                string password = mailSettings.Smtp.Network.Password;
                string username = mailSettings.Smtp.Network.UserName;
                mail.displayname = GlobalConfig.GetStringSetting("DisplayNameEmail");
                using (MailMessage mm = new MailMessage())
                {
                    mm.Subject    = mail.subject;
                    mm.Body       = mail.body;
                    mm.IsBodyHtml = true;
                    mm.From       = new MailAddress(username, mail.displayname);
                    mm.To.Add(mail.mailto);
                    smtp.Host                  = host;
                    smtp.EnableSsl             = true;
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials           = new NetworkCredential(username, password);
                    smtp.Port                  = port;
                    smtp.Send(mm);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Loger.Log(ex.ToString());
                return(false);
            }
            finally
            {
                smtp.Dispose();
            }
        }
コード例 #29
0
        public static bool _SendMail(MailModel value)
        {
            MailSettings appSettings = new MailSettings
            {
                Host     = "smtp.gmail.com",
                Port     = 587,
                UserName = "******",
                Password = "******",
                SSL      = true,
                Sender   = "*****@*****.**"
            };

            try
            {
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(appSettings.Sender);
                mail.To.Add(value.To);
                mail.Subject = value.Subject;
                mail.Body    = value.Body;
                value.Copy.ToList().ForEach(mail.CC.Add);
                //mail.Attachments.Add(new Attachment(@"C:\teste.txt"));

                using (var smtp = new SmtpClient(appSettings.Host))
                {
                    smtp.EnableSsl             = appSettings.SSL;
                    smtp.Port                  = appSettings.Port;
                    smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                    smtp.UseDefaultCredentials = false;

                    // seu usuário e senha para autenticação
                    smtp.Credentials = new NetworkCredential(appSettings.UserName, appSettings.Password);

                    // envia o e-mail
                    smtp.Send(mail);
                }
                return(true);
            }
            catch (Exception ex)
            {
                Console.Write("Exception:");
                Console.Write($"Message: {ex.Message}, InnerException: {ex.InnerException}");
                return(false);
            }
        }
コード例 #30
0
        /// <summary>
        /// Send mail
        /// </summary>
        /// <param name="model"></param>
        public static void SendMail(MailModel model)
        {
            try
            {
                MailMessage mail = new MailMessage();

                SmtpClient SmtpServer = new SmtpClient(Constants.SMTPCLIENT_MAIL_RU);

                mail.From = new MailAddress(Constants.MAIL_ADDRESS);
                if (model.ToMail != null && model.ToMail.Count >= 1)
                {
                    foreach (var item in model.ToMail)
                    {
                        mail.To.Add(item);
                    }
                }
                else
                {
                    mail.To.Add(Constants.MAIL_ADDRESS);
                }

                mail.Subject = model.Subject;

                if (model.Subject.Equals("Contact Us"))
                {
                    mail.Body = "Name: " + model.Name + ", Email: " + model.YourMail + ", Phone Number: " + model.Phone + ", Mail Body: " + model.Body;
                }
                else
                {
                    mail.Body = model.Body;
                }

                SmtpServer.Port        = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential(Constants.MAIL_ADDRESS, Constants.MAIL_PASSWORD);

                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #31
0
        public FileResult DownloadMailAttachment(string mailId, string subPath, int idx)
        {
            ValidateMailId(mailId);
            subPath = subPath ?? "";
            ValidateSubPath(subPath);
            var filePath = Path.Combine(Properties.Settings.Default.MailDir, subPath, mailId);

            if (!MailHelper.ListMailFiles(Path.Combine(Properties.Settings.Default.MailDir, subPath)).Select(f => f.FullName).Contains(filePath))
            {
                throw new ArgumentException("mailId is not in white list", nameof(mailId));
            }

            var mail = new MailModel(filePath);

            var result = File(mail.GetAttachmentContentFromIdx(idx), mail.GetAttachmentMediaTypeFromIdx(idx));

            result.FileDownloadName = mail.AttachmentNames[idx];
            return(result);
        }
コード例 #32
0
        private bool SendMail_AlertMail(MailModel mailModel)
        {
            mailModel.From = "*****@*****.**";
            string            subject            = mailModel.Subject;
            NetworkCredential networkCredential1 = new NetworkCredential();
            string            smtpIp             = ConfigurationManager.AppSettings["SMTP_IP"];
            int smtpIpPort = int.Parse(ConfigurationManager.AppSettings["SMTP_IP_Port"]); //this.SMTP_IP_Port;
            NetworkCredential networkCredential2 = new NetworkCredential("firstalert", "password2$", "hocdc-05.nigeria.firstbank.local");
            SmtpClient        smtpClient         = new SmtpClient(smtpIp, smtpIpPort);
            Exception         exception;

            try
            {
                string body = mailModel.MailContent;
                string str1 = "";
                string str2 = " <img src=cid:Image1 /> ";
                str1 = " <img src=cid:Image2 /> ";
                AlternateView  alternateViewFromString = AlternateView.CreateAlternateViewFromString((str2 + body).ToString(), (Encoding)null, "text/html");
                LinkedResource linkedResource          = new LinkedResource("~/assets/img/Logo1.jpg");
                linkedResource.ContentId = "Image1";
                alternateViewFromString.LinkedResources.Add(linkedResource);
                MailMessage message = new MailMessage(mailModel.From, mailModel.To, subject, body);
                try
                {
                    message.CC.Add(new MailAddress(mailModel.CC));
                }
                catch (Exception ex)
                {
                    exception = ex;
                }
                message.IsBodyHtml = true;
                message.AlternateViews.Add(alternateViewFromString);
                smtpClient.UseDefaultCredentials = true;
                smtpClient.Credentials           = (ICredentialsByHost)networkCredential2;
                smtpClient.Send(message);
                return(true);
            }
            catch (Exception ex)
            {
                exception = ex;
                return(false);
            }
        }
コード例 #33
0
        public ActionResult SendMessage(MailModel md)
        {
            const string SERVER  = "relay-hosting.secureserver.net";
            const string TOEMAIL = "*****@*****.**";
            MailAddress  from    = new MailAddress(md.E_mail);
            MailAddress  to      = new MailAddress(TOEMAIL);
            MailMessage  message = new MailMessage(from, to);

            message.Subject = "Web Site Contact Inquiry from " + md.Name;
            message.Body    = "Message from: " + md.Name + " at " +
                              md.E_mail + "\n\n" + md.Message;
            message.IsBodyHtml = false;
            SmtpClient client = new SmtpClient(SERVER);

            client.Send(message);

            //commented part is for testing purposes

            //var fromAddress = new MailAddress("*****@*****.**", md.Name);
            //var toAddress = new MailAddress("*****@*****.**", "To Name");
            //const string fromPassword = "******";
            //const string subject = "test";
            //string body = md.Message;

            //var smtp = new SmtpClient
            //{
            //    Host = "smtp.gmail.com",
            //    Port = 587,
            //    EnableSsl = true,
            //    DeliveryMethod = SmtpDeliveryMethod.Network,
            //    Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
            //    Timeout = 20000
            //};
            //using (var message = new MailMessage(fromAddress, toAddress)
            //{
            //    Subject = subject,
            //    Body = body
            //})
            //{
            //    smtp.Send(message);
            //}
            return(null);
        }
コード例 #34
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext == null)
                throw new ArgumentNullException("controllerContext");

            if (bindingContext == null)
                throw new ArgumentNullException("bindingContext");

            var retVal = new MailModel();

            var form = controllerContext.RequestContext.HttpContext.Request.Form;
            var allKeys = form.AllKeys.ToList();
            allKeys.Remove("returnUrl");
            allKeys.Remove("vendore");

            CheckAndRemoveKeys(allKeys);

            if (allKeys.Contains("fullname"))
                retVal.FullName = form["fullname"];

            retVal.To = form["to"];
            retVal.Subject = form["subject"];

            var builder = new StringBuilder();
            foreach (var key in allKeys)
            {
                builder.AppendLine(string.Format("{0}: {1} <br>", key, form[key]));
            }

            retVal.MailBody = builder.ToString();

            builder.AppendLine(string.Format("EmailTo: {0}", form["to"]));
            retVal.FullMailBody = builder.ToString();

            return retVal;
        }
コード例 #35
0
ファイル: MailTemplate.cs プロジェクト: ChadBurggraf/tasty
        /// <summary>
        /// Transforms the given model using this instance's template.
        /// </summary>
        /// <param name="model">The model to transform.</param>
        /// <param name="writer">The <see cref="XmlWriter"/> to write the results of the transformation to.</param>
        public void Transform(MailModel model, XmlWriter writer)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model", "model cannot be null.");
            }

            if (writer == null)
            {
                throw new ArgumentNullException("writer", "writer cannot be null.");
            }

            XmlDocument stylesheet = new XmlDocument();
            stylesheet.Load(this.templateStream);

            XslCompiledTransform transform = new XslCompiledTransform();
            transform.Load(stylesheet);

            transform.Transform(model.ToXml(), writer);
        }
コード例 #36
0
ファイル: MailTemplate.cs プロジェクト: ChadBurggraf/tasty
        /// <summary>
        /// Transforms the given model using this instance's template.
        /// </summary>
        /// <param name="model">The model to transform.</param>
        /// <returns>A string of XML representing the transformed model.</returns>
        public string Transform(MailModel model)
        {
            StringBuilder sb = new StringBuilder();

            using (StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture))
            {
                using (XmlWriter xw = new XmlTextWriter(sw))
                {
                    this.Transform(model, xw);
                }
            }

            return sb.ToString();
        }
コード例 #37
0
ファイル: Emailer.cs プロジェクト: ChadBurggraf/tasty
        /// <summary>
        /// Sends the email(s) current configured by this instance.
        /// </summary>
        /// <param name="model">The model to use when sending email.
        /// WARNING: The model's <see cref="MailModel.Email"/> property will be set for each recipient.</param>
        public void Send(MailModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model", "model cannot be null.");
            }

            this.Validate();
            SmtpClient client = this.CreateClient();
            string body = this.template.Transform(model);

            using (MailMessage message = this.CreateMessage())
            {
                foreach (string to in this.To)
                {
                    model.Email = to;
                    message.To.Clear();
                    message.To.Add(to);
                    message.Body = body;
                    client.Send(message);

                    this.RaiseEvent(this.Sent, new EmailSentEventArgs(to));
                }

                this.RaiseEvent(this.AllSent, EventArgs.Empty);
            }
        }
コード例 #38
0
ファイル: Emailer.cs プロジェクト: ChadBurggraf/tasty
        /// <summary>
        /// Sends the email(s) current configured by this instance.
        /// WARNING: A giant assumption is made that changes to the <see cref="To"/> collection will not be made
        /// while this call is in progress, as well as that no other calls to <see cref="Send(MailModel)"/>
        /// or <see cref="SendAsync(MailModel)"/> are made on this instance while this call is in progress.
        /// </summary>
        /// <param name="model">The model to use when sending email.
        /// WARNING: The model's <see cref="MailModel.Email"/> property will be set for each recipient.</param>
        public void SendAsync(MailModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model", "model cannot be null.");
            }

            this.Validate();

            Thread thread = new Thread(new ParameterizedThreadStart(delegate(object state)
            {
                using (MailMessage message = this.CreateMessage())
                {
                    foreach (string to in this.To)
                    {
                        model.Email = to;
                        message.Body = this.template.Transform(model);

                        SmtpClient client = this.CreateClient();
                        client.SendCompleted += new SendCompletedEventHandler(this.ClientSendCompleted);
                        client.SendAsync(message, to);
                    }
                }
            }));

            thread.Start();
        }