public override void initConfig(JObject config) { JToken cfg = config["TaskList"].Where(p => p["taskName"].ToString() == name()).ToArray()[0]["taskInfo"]; auctionStateChangeCol = cfg["auctionStateChangeCol"].ToString(); notifySubsColl = cfg["notifySubsCol"].ToString(); batchSize = int.Parse(cfg["batchSize"].ToString()); batchInterval = int.Parse(cfg["batchInterval"].ToString()); var mailCfg = cfg["mailInfo"]; mailConfig = new MailConfig { mailFrom = mailCfg["mailFrom"].ToString(), mailPwd = mailCfg["mailPwd"].ToString(), smtpHost = mailCfg["smtpHost"].ToString(), smtpPort = int.Parse(mailCfg["smtpPort"].ToString()), authCodeSubj = mailCfg["authCodeSubj"].ToString(), authCodeBody = mailCfg["authCodeBody"].ToString(), domainNotifySubj = mailCfg["domainNotifySubj"].ToString(), domainNotifyBody = mailCfg["domainNotifyBody"].ToString(), }; // db info remoteDbConnInfo = Config.notifyDbConnInfo; // new Task(() => sendThread()).Start(); initSuccFlag = true; }
/// <summary> /// 发送邮件 /// </summary> /// <param name="mailConfig"></param> /// <param name="mailInfo"></param> /// <returns></returns> public static bool Send(MailConfig mailConfig, MailInfo mailInfo) { var message = new MailMessage(); if (!string.IsNullOrEmpty(mailInfo.AttachmentAddress)) { message.Attachments.Add(new Attachment(mailInfo.AttachmentAddress)); } foreach (var address in mailInfo.Recipients) { message.To.Add(new MailAddress(address)); } message.From = new MailAddress(mailConfig.SenderAddress, mailConfig.SenderDisplayName); message.BodyEncoding = Encoding.GetEncoding(mailInfo.Encoding); message.Body = mailInfo.Body; message.SubjectEncoding = Encoding.GetEncoding(mailInfo.Encoding); message.Subject = mailInfo.Subject; message.IsBodyHtml = mailInfo.IsBodyHtml; var smtpclient = new SmtpClient(mailConfig.MailHost, mailConfig.MailPort.ToInt()); smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpclient.Credentials = new System.Net.NetworkCredential(mailConfig.SenderUserName, mailConfig.SenderPassword); smtpclient.EnableSsl = mailInfo.EnableSsl; smtpclient.Send(message); return(true); }
public ActionResult Edit([Bind(Include = "ID,EmailAddress,Password,Port,Host,EnabledSSL,TemplateID,CreatedAt,UpdatedAt,Active")] MailConfig mailConfig) { try { var validateName = _mailConfigService.GetAll().FirstOrDefault (x => x.EmailAddress == mailConfig.EmailAddress && x.ID != mailConfig.ID); if (validateName != null) { ModelState.AddModelError("EmailAddress", "Email Address already exists"); } if (ModelState.IsValid) { string password = MailHelper.Encrypt(mailConfig.Password); mailConfig.Password = password; mailConfig.UpdatedAt = DateTime.Now; db.Entry(mailConfig).State = EntityState.Modified; db.SaveChanges(); SetAlert("Update Mail Config success", "success"); return(RedirectToAction("Index")); } }catch (Exception e) { SetAlert("Update Mail Config error", "error"); } return(View(mailConfig)); }
public Task SendAsync(IdentityMessage message) { // Plug in your email service here to send an email. // return Task.FromResult(0); // return configSendGridasync(message); MailConfig mailConfig = (MailConfig)ConfigurationManager.GetSection("application/mail"); if (mailConfig.RequireValid) { // 设置邮件内容 var mail = new MailMessage( new MailAddress(mailConfig.Uid, "毕业设计"), new MailAddress(message.Destination)); mail.Subject = message.Subject; mail.Body = message.Body; mail.IsBodyHtml = true; mail.BodyEncoding = Encoding.UTF8; // 设置SMTP服务器 var smtp = new SmtpClient(mailConfig.Server, mailConfig.Port); smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtp.UseDefaultCredentials = false; smtp.Credentials = new System.Net.NetworkCredential(mailConfig.Uid, mailConfig.Pwd); return(smtp.SendMailAsync(mail)); } return(Task.FromResult(0)); }
private void AddAttachments(MailConfig config, MailMessage mailMessage) { foreach (var attachment in config.Attachments) { mailMessage.Attachments.Add(new Attachment(attachment.Value, attachment.Key)); } }
public static void SendMail(MailConfig config, string msg) { MailAddress mailAddress = new MailAddress(config.Address); MailMessage mailMessage = new MailMessage(); foreach (var item in config.ReceiveList) { if (!string.IsNullOrEmpty(item)) { mailMessage.To.Add(item.ToString()); } } mailMessage.From = mailAddress; mailMessage.Subject = "FuckWayne"; mailMessage.SubjectEncoding = Encoding.UTF8; mailMessage.Body = msg; mailMessage.BodyEncoding = Encoding.Default; mailMessage.Priority = MailPriority.High; mailMessage.IsBodyHtml = false; SmtpClient smtp = new SmtpClient(); smtp.Credentials = new System.Net.NetworkCredential(config.Address, config.Password); smtp.Host = config.Host; smtp.Send(mailMessage); }
/// <summary> /// 获取邮箱配置 /// </summary> /// <returns></returns> public static MailConfig GetMailConfig(Vault vault) { var defConfig = new MailConfig { RecvPort = MailConfig.PopDefPort, SendPort = MailConfig.SmtpDefPort, }; try { var result = SearchMailConfig(vault); if (result.Count > 0) { var configs = new List <MailConfig>(); foreach (ObjectVersion obj in result) { var config = new MailConfig(); var properties = vault.ObjectPropertyOperations.GetProperties(obj.ObjVer, false); SetMailConfigItem(vault, config, properties); configs.Add(config); } return(configs[0]); } return(defConfig); } catch (Exception ex) { Logger.Log.ErrorFormat("exception. get email config from mfiles error: {0}", ex.Message); return(defConfig); } }
private static void SendWelcomeEmail(string userEmail) { var config = new MailConfig(); if (config.Host == null) { Error.Log(new Exception(), "SMTP host is null"); return; } var client = new SmtpClient() { Host = config.Host, Port = config.Port, Credentials = new NetworkCredential(config.Login, config.Password), EnableSsl = true, }; try { client.Send(new MailMessage(config.Login, userEmail) { Subject = "Thank you for registering", Body = "Thank you for registering in our app. We hope you'll have a great time!" }); } catch (Exception exception) { Error.Log(exception); } }
private MimeMessage GetMailMessage(MailConfig config) { var message = new MimeMessage(); message.To.AddRange(config.To.Select(x => new MailboxAddress(string.Empty, x))); message.From.Add(new MailboxAddress(string.Empty, config.From)); message.Subject = config.Subject; TextPart body; if (config.EmailFormat == EmailFormatType.Html) { body = new TextPart(MimeKit.Text.TextFormat.Html); } else { body = new TextPart(MimeKit.Text.TextFormat.Text); } body.Text = config.Body; Multipart multipart; if (config.Attachments.Count > 0) { multipart = new Multipart("mixed"); } else { multipart = new Multipart(); } multipart.Add(body); message.Body = multipart; AddAttachments(config, multipart); return(message); }
private async void MainFrm_Load(object sender, EventArgs e) { this.lblStatus.Text = "正在读取邮箱配置..."; await Task.Run(() => { _vault = MailCore.MF.MFilesUtil.GetVaultByName(); _config = MailCore.MF.MfMailConfig.GetMailConfig(_vault); }); if (String.IsNullOrEmpty(_config.Email)) { MessageBox.Show("邮件地址为空,请先点击“设置”配置邮箱信息!", "收信", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); this.Close(); } if (String.IsNullOrEmpty(_config.RecvAddr)) { MessageBox.Show("POP服务器地址为空,请先点击“设置”配置邮箱信息!", "收信", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); this.Close(); } _bkWorker.DoWork += BkWorkerOnDoWork; _bkWorker.ProgressChanged += BkWorkerOnProgressChanged; _bkWorker.RunWorkerCompleted += BkWorkerOnRunWorkerCompleted; _bkWorker.RunWorkerAsync(); }
private static MailMessage GetMailMessage(MailInfo mailInfo, MailConfig mailSettings) { MailMessage message = new MailMessage(); foreach (MailAddress address in mailInfo.MailToAddressList) { message.To.Add(address); } if (mailInfo.MailCopyToAddressList != null) { foreach (MailAddress address2 in mailInfo.MailCopyToAddressList) { message.CC.Add(address2); } } if (mailInfo.ReplyTo != null) { message.ReplyTo = mailInfo.ReplyTo; } if (!string.IsNullOrEmpty(mailInfo.FromName)) { message.From = new MailAddress(mailSettings.MailFrom, mailInfo.FromName); } else { message.From = new MailAddress(mailSettings.MailFrom); } message.Subject = mailInfo.Subject; message.SubjectEncoding = Encoding.UTF8; message.Body = mailInfo.MailBody; message.BodyEncoding = Encoding.UTF8; message.Priority = mailInfo.Priority; message.IsBodyHtml = mailInfo.IsBodyHtml; return(message); }
public virtual MailLogDTO SendMail(Domain.Entity.Client currentClient, MailModel entity, object param) { List <string> recipients = new List <string>(); List <Document> documents = new List <Document>(); MailLog mailLog; ValidateNull(entity); if (!validation.PreValidatePost(validationDictionnary, currentClient, entity, param, repo, recipients, documents)) { throw new ManahostValidationException(validationDictionnary); } IHomeRepository homeRepo = ((MailController.AdditionalRepositories)param).HomeRepo; MailConfig mailconfig = repo.GetMailConfigById(entity.MailConfigId, currentClient.Id); Mailling.SendMailBcc(new InfosMailling(mailconfig.Smtp, (int)mailconfig.SmtpPort, mailconfig.Email, homeRepo.GetHomeById(mailconfig.HomeId, currentClient.Id).Title, Encoding.UTF8.GetString(Convert.FromBase64String(entity.Password))) { body = entity.Body, prio = System.Net.Mail.MailPriority.Normal, subject = entity.Subject, toPeople = recipients, ssl = (bool)mailconfig.IsSSL, attachments = MailUtils.GetAttachments(documents, mailconfig.Home) }, mailLog = new MailLog() { DateSended = DateTime.UtcNow, To = String.Join(",", recipients.ToArray()), Successful = true, HomeId = mailconfig.HomeId }); repo.Add <MailLog>(mailLog); return(GetMapper.Map <MailLog, MailLogDTO>(mailLog)); }
public async void RendersDailyViewWithViewModel() { var items = new List <Item>() { new Item { } }.AsEnumerable(); var mockContentService = new Mock <IContentService>(); mockContentService.Setup(x => x.GetDailyItemsAsync(It.IsAny <DateTime>())).ReturnsAsync(items); var mockViewRenderer = new Mock <IViewRenderer>(); var mailConfig = new MailConfig { DailySubject = "" }; var mailController = new MailController(new FakeMailChimpManager().Object, Mock.Of <IMailService>(), mockContentService.Object, mockViewRenderer.Object, new FakeBankHolidayService(), Mock.Of <ILogger <MailController> >(), mailConfig, TestAppSettings.MailChimp.Default); //Act await mailController.PutDailyMailAsync(); //Assert // TODO: Assert on the actual view model mockViewRenderer.Verify(mock => mock.RenderViewAsync(mailController, "~/Views/Mail/Daily.cshtml", It.IsAny <DailyEmailViewModel>(), false), Times.Once()); }
private void AddAttachments(MailConfig config, SendGridMessage mailMessage) { foreach (var attachment in config.Attachments) { mailMessage.AddAttachmentAsync(attachment.Key, attachment.Value); } }
public static void MailConfig(MailConfig config) { smtpClientHost = config.SmtpClientHost; smtpClientPort = config.SmtpClientPort; mailLogin = config.MailLogin; mailPassword = config.MailPassword; }
public Task SendAsync(MailConfig config) { var mailMessage = GetMailMessage(config); SendClient.SendEmailAsync(mailMessage); return(Task.CompletedTask); }
private void btnSave_Click(object sender, EventArgs e) { if (txtCode.Text.Trim() == "") { MessageBox.Show("Vui lòng nhập mã profile", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (mailConfig == null && status == "NEW") { MailConfig cf = GetFormInfo(); if (chkDefault.Checked) { MailConfig.ResetDefault(); } long ID = MailConfig.Insert(cf); MessageBox.Show("Thêm mới profile thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); LoadMailSetting(); } else if (mailConfig != null && status == "EDIT") { MailConfig cf = GetFormInfo(); if (chkDefault.Checked) { MailConfig.ResetDefault(); } cf.ID = mailConfig.ID; MailConfig.Update(cf); mailConfig = cf; MessageBox.Show("Cập nhập profile thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public SignEditor(MFilesAPI.Vault vault, MailConfig config) { InitializeComponent(); _vault = vault; _config = config; Load += OnLoad; }
public async Task <MailResult> SendMailAsync(MailConfig mailConfig) { var apiKey = mailConfig.Password; var client = new SendGridClient(apiKey); return(await client.SendEmailAsync(mailConfig)); }
public MailService(IMailChimpManager mailChimpManager, ILogger <MailService> logger, MailChimpConfig mailChimpConfig, MailConfig mailConfig) { _mailChimpManager = mailChimpManager; _logger = logger; _mailChimpConfig = mailChimpConfig; _mailConfig = mailConfig; }
//This will Send Mail to User notifying him his password public string SendMail(AuthModel authModel, string password, string type) { MailModel mailModel = new MailModel(); mailModel.MailTo = authModel.Email; mailModel.MailSubject = "Welcome to The Phone Store"; mailModel.MailBody = "<h2>hello " + authModel.Name + "</h2>" + "<h3>welcome to the Store. " + type + " </br> " + "The Random Password for you Sign in is <b>" + password + "</b></h3>" + "<p>Thank You for Staying With us</p>" + "Mail Sent at " + authModel.IssueDate + "</br>" + "@copyright Shuorer Baccha "; MailConfig conf = new MailConfig(); string mailStatus = conf.sendUserPassword(mailModel); if (mailStatus == "OK") { return("Success"); } else { return(mailStatus); } }
public MailService(MailConfig config, ICompositeViewEngine viewEngine, ITempDataProvider tempDataProvider, IServiceProvider serviceProvider) { _config = config; _viewEngine = viewEngine; _tempDataProvider = tempDataProvider; _serviceProvider = serviceProvider; }
public ActionResult DeleteConfirmed(int id) { MailConfig mailConfig = db.MailConfig.Find(id); db.MailConfig.Remove(mailConfig); db.SaveChanges(); return(RedirectToAction("Index")); }
private SmtpClient CreateClient(MailConfig config) { return(new SmtpClient { Host = config.SmtpServer, Port = config.Port, }); }
private void btnNew_Click(object sender, EventArgs e) { lkProfile.EditValue = null; ClearFormInfo(); mailConfig = null; SetFormStatus("NEW"); btnDelete.Enabled = false; }
/// <summary> /// /// </summary> /// <param name="context"></param> public void OnException(ExceptionContext context) { try { var ex = context.Exception; _logger.LogError(context.Exception, ex.Message ?? ""); //发送邮件提醒 var settings = _settingService.GetMasterSettings(); if (!String.IsNullOrEmpty(settings.ErrorToMailAddress)) { string[] mails = mails = new string[] { settings.ErrorToMailAddress }; if (settings.ErrorToMailAddress.Contains(";")) { mails = settings.ErrorToMailAddress.Split(";"); } var config = new MailConfig() { Account = settings.EmailAccount, Host = settings.EmailHost, Password = settings.EmailPassword }; if (int.TryParse(settings.EmailPort, out int _port)) { config.Port = _port; _mailProvide.Smtp(config, mails, $"{settings.SiteName}系统错误提醒", ex.Message + Environment.NewLine + ex.StackTrace); } } } catch (Exception) { } switch (_platform) { //web页面 case 0: if (context.HttpContext.Request.IsAjaxRequest()) { context.Result = new JsonResult(new AjaxResult() { Code = 1001, Message = "系统错误,请稍后重试" }); } else { context.Result = new ViewResult() { ViewName = "Error" }; } break; //api case 1: context.Result = new OkObjectResult(new ApiJsonResult() { code = 1001, msg = "系统错误,请稍后重试" }); break; } }
static void Init() { //初始化重试器 _retryTwoTimesPolicy = Policy .Handle <Exception>() .Retry(3, (ex, count) => { _logger.Error("Excuted Failed! Retry {0}", count); _logger.Error("Exeption from {0}", ex.GetType().Name); }); //获取应用程序所在目录 Type type = (new Program()).GetType(); _baseDir = Path.GetDirectoryName(type.Assembly.Location); //检查工作目录 if (!Directory.Exists(Path.Combine(_baseDir, "Blogs"))) { Directory.CreateDirectory(Path.Combine(_baseDir, "Blogs")); } //初始化记录时间 _recordTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 9, 0, 0); //初始化日志 LogManager.Configuration = new XmlLoggingConfiguration(Path.Combine(_baseDir, "Config", "NLog.Config")); _logger = LogManager.GetLogger("CnBlogSubscribeTool"); _sendLogger = LogManager.GetLogger("MailSend"); //初始化邮件配置 _mailConfig = JsonConvert.DeserializeObject <MailConfig>( File.ReadAllText(Path.Combine(_baseDir, "Config", "Mail.json"))); //加载最后一次成功获取数据缓存 _tmpFilePath = Path.Combine(_baseDir, "Blogs", "cnblogs.tmp"); if (File.Exists(_tmpFilePath)) { try { var data = File.ReadAllText(_tmpFilePath); var res = JsonConvert.DeserializeObject <List <Blog> >(data); if (res != null) { PreviousBlogs.AddRange(res); } } catch (Exception e) { _logger.Error("缓存数据加载失败,本次将弃用!详情:" + e.Message); File.Delete(_tmpFilePath); } } }
static void Init() { Type type = (new Program()).GetType(); _baseDir = Path.GetDirectoryName(type.Assembly.Location); _mailConfig = NewLife.Serialization.JsonHelper.ToJsonEntity <MailConfig>( File.ReadAllText(Path.Combine(_baseDir, "Config", "Mail.json"))); }
public TransactionalMailHelper(SendGridService sendGridService, IMailConfigStorage mailConfigStorage, WorkspaceAppService workspaceAppService) { _fromAddress = new EmailAddress("Team at Project Unicorn", "*****@*****.**"); _testEmailIndicator = AppSettings.Env == "Staging" || AppSettings.Env == "Development" ? "[TEST EMAIL] " : ""; _sendGridService = sendGridService; _mailConfig = new MailConfig(mailConfigStorage); _userStorage = new UserEntity(); _workspaceAppService = workspaceAppService; }
public void DeleteMailConfig() { MailConfig toDelete = ctx.MailConfigSet.FirstOrDefault(p => p.Title == "myemail"); repo.Delete(toDelete); repo.Save(); Assert.IsNull(ctx.MailConfigSet.FirstOrDefault(p => p.Title == "myemail")); }
private bool SendMail(string to, string subject, string url, MailConfig pmc) { DateTime before = DateTime.Now; try { CDO.Message msg = new CDO.Message(); CDO.Configuration conf = msg.Configuration; Fields fs = conf.Fields; #region Set field values fs["http://schemas.microsoft.com/cdo/configuration/languagecode"].Value = "hu"; fs["http://schemas.microsoft.com/cdo/configuration/postusing"].Value = CdoPostUsing.cdoPostUsingPort; fs["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].Value = pmc.sendemailaddress; fs["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value = pmc.sendpassword; fs["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value = pmc.sendusername; fs["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = CdoSendUsing.cdoSendUsingPort; fs["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].Value = "Zoznam"; fs["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value = CdoProtocolsAuthentication.cdoBasic; fs["http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout"].Value = 10; fs["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = pmc.smtpserver; fs["http://schemas.microsoft.com/cdo/configuration/smtpserverport"].Value = pmc.smtpport; fs["http://schemas.microsoft.com/cdo/configuration/usemessageresponsetext"].Value = true; fs["http://schemas.microsoft.com/cdo/configuration/smtpusessl"].Value = false; fs["urn:schemas:calendar:timezoneid"].Value = CdoTimeZoneId.cdoEasternEurope; #endregion fs.Update(); msg.Subject = subject; Trace.WriteLine("Downloading email body from feed page..."); lblSendStatus.Text = "Send status: Downloading email body from feed page..."; msg.CreateMHTMLBody(url, CdoMHTMLFlags.cdoSuppressNone, null, null); msg.To = to; Trace.WriteLine("Sending message..."); lblSendStatus.Text = "Send status: Sending message..."; msg.Send(); TimeSpan total = DateTime.Now.Subtract(before); Trace.WriteLine("Message sent successfully. Total time: " + total.ToString()); lblSendStatus.Text = "Send status: Message sent successfully. Total time: " + total.ToString(); return true; } catch (COMException cex) { Trace.WriteLine(cex.ToString()); return false; } }