public void Send(SmtpSettings settings, string from, string to, string subject, string body) { try { var fromAddress = new MailAddress(from); var toAddress = new MailAddress(to); string fromPassword = settings.Password; var smtp = new SmtpClient { Host = settings.Host, Port = settings.Port, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(settings.Username, settings.Password) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body, IsBodyHtml = true }) { smtp.Send(message); //return smtp.SendMailAsync(message); } } catch (Exception ex) { throw ex; } }
public static void SendRegistrationConfirmationLink( SmtpSettings smtpSettings, string messageTemplate, string fromEmail, string fromAlias, string userEmail, string siteName, string confirmationLink) { StringBuilder message = new StringBuilder(); message.Append(messageTemplate); message.Replace("{SiteName}", siteName); message.Replace("{AdminEmail}", fromEmail); message.Replace("{UserEmail}", userEmail); message.Replace("{ConfirmationLink}", confirmationLink); Email.Send( smtpSettings, fromEmail, fromAlias, string.Empty, userEmail, string.Empty, string.Empty, siteName, message.ToString(), false, "Normal"); }
public void UnconvertableSettingResultsInFormatException() { var settingsSource = new NameValueCollection(); settingsSource["Smtp:Port"] = "abcdef"; var reader = new SimpleSettingsReader(settingsSource); var injector = new SimpleSettingsInjector(); var settings = new SmtpSettings(); injector.Inject(settings, reader); Assert.Fail("Should have thrown"); }
public void CanReadTypesOtherThanString() { var settingsSource = new NameValueCollection(); settingsSource["Smtp:Server"] = "fake-server"; settingsSource["Smtp:Port"] = "12345"; settingsSource["Smtp:UseSSL"] = "True"; var injector = new SimpleSettingsInjector(); var reader = new SimpleSettingsReader(settingsSource); var settings = new SmtpSettings(); injector.Inject(settings, reader); Assert.AreEqual("fake-server", settings.Server); Assert.AreEqual(12345, settings.Port); Assert.IsTrue(settings.UseSSL); }
public void CanReadManySettingsFromASingleSource() { var settingsSource = new NameValueCollection(); settingsSource["Smtp:Server"] = "test-server"; settingsSource["My:Name"] = "Mike"; var reader = new SimpleSettingsReader(settingsSource); var injector = new SimpleSettingsInjector(); var smtpSettings = new SmtpSettings(); var mySettings = new MySettings(); injector.Inject(smtpSettings, reader); injector.Inject(mySettings, reader); Assert.AreEqual("test-server", smtpSettings.Server); Assert.AreEqual("Mike", mySettings.Name); }
public AppSettings() { _settings = new NameValueCollection(ConfigurationManager.AppSettings); var missing = Values.FirstOrDefault(kvp => kvp.Value.ToUpper().Trim() == "#TBD"); if(missing.Key != null) { throw new ConfigurationErrorsException( "Missing required configuration value {0}".FormatFrom(missing.Key)); } _settings = _settings.ExpandTokens(); Server = new ServerSettings(_settings); Git = new GitSettings(_settings); Env = new EnvSettings(_settings); Smtp = new SmtpSettings(_settings); }
public static void SendBlogCommentNotificationEmail( SmtpSettings smtpSettings, string messageTemplate, string fromEmail, string siteName, string authorEmail, string messageLink) { StringBuilder message = new StringBuilder(); message.Append(messageTemplate); message.Replace("{SiteName}", siteName); message.Replace("{MessageLink}", messageLink); Email.SendEmail( smtpSettings, fromEmail, authorEmail, "", "", siteName, message.ToString(), false, "Normal"); }
public static void SendPassword( SmtpSettings smtpSettings, string messageTemplate, string fromEmail, string userEmail, string userPassword, string siteName, string siteLink) { StringBuilder message = new StringBuilder(); message.Append(messageTemplate); message.Replace("{SiteName}", siteName); message.Replace("{AdminEmail}", fromEmail); message.Replace("{UserEmail}", userEmail); message.Replace("{UserPassword}", userPassword); message.Replace("{SiteLink}", siteLink); Email.SendEmail( smtpSettings, fromEmail, userEmail, "", "", siteName, message.ToString(), false, "Normal"); }
public EmailSender(IOptions <SmtpSettings> smtpSettings) { _smtpSettings = smtpSettings.Value; }
protected BaseEmailService(ILogManager logManager, SmtpSettings smtpSettings) { _logManager = logManager; _smtpClient = new SmtpClient(); SetSmtpSettings(smtpSettings); }
public MailSenderService(IOptions <SmtpSettings> smtpSettings, IEmailService emailService) { _smtpSettings = smtpSettings.Value; _emailService = emailService; }
private bool ValidateSmtpSetting(SmtpSettings value, out string message) => ValidateOptionalEntry($"{Constants.Configuration.ConfigGlobal}:{nameof(GlobalSettings.Smtp)}", value, "A valid From email address is required", out message);
public MailSender(AppSettings appSettingsOptions) { smtpSettings = appSettingsOptions.MailSettings.SmtpSettings; }
private void RunTask() { Letter letter = new Letter(this.letterGuid); if (letter.LetterGuid == Guid.Empty) { log.Error("LetterSendTask letter not found so ending."); ReportStatus(); return; } if (letter.SendCompleteUtc > DateTime.MinValue) { log.Error("LetterSendTask SendCompleteUtc already set so ending."); ReportStatus(); return; } if (letter.SendClickedUtc == DateTime.MinValue) { log.Error("LetterSendTask SendClickedUtc has an invalid value so ending."); ReportStatus(); return; } LetterInfo letterInfo = new LetterInfo(letter.LetterInfoGuid); SubscriberRepository subscriptions = new SubscriberRepository(); if (WebConfigSettings.NewsletterTestMode) { testMode = true; log.Info("using NewsletterTestMode=true in config so no real emails will be sent for newsletter " + letterInfo.Title); } // TODO: this could be a very large recordset if the list is very large // might be better to get a page at a time instead of all at once. List<LetterSubscriber> subscribers = subscriptions.GetSubscribersNotSentYet( letter.LetterGuid, letter.LetterInfoGuid); nextStatusUpdateTime = DateTime.UtcNow.AddSeconds(reportingFrequency); totalSubscribersToSend = subscribers.Count; if ((totalSubscribersToSend > 0) && (letter.SendStartedUtc == DateTime.MinValue)) { letter.TrackSendStarted(); } if (totalSubscribersToSend < 100) { testSleepMilliseconds = 3000; } if (totalSubscribersToSend > 300) { testSleepMilliseconds = 500;} if (totalSubscribersToSend > 500) { testSleepMilliseconds = 100; } SmtpSettings smtpSettings = new SmtpSettings(); smtpSettings.Password = password; smtpSettings.Port = port; smtpSettings.PreferredEncoding = preferredEncoding; smtpSettings.RequiresAuthentication = requiresAuthentication; smtpSettings.UseSsl = useSsl; smtpSettings.User = user; smtpSettings.Server = server; smtpSettings.AddBulkMailHeader = true; if (maxToSendPerMinute == 0) //not limit { foreach (LetterSubscriber subscriber in subscribers) { SendLetter(smtpSettings, letterInfo, letter, subscriber); subscribersSentSoFar += 1; if (DateTime.UtcNow > nextStatusUpdateTime) ReportStatus(); } } else { int sentCount = 0; foreach (LetterSubscriber subscriber in subscribers) { SendLetter(smtpSettings, letterInfo, letter, subscriber); subscribersSentSoFar += 1; sentCount += 1; if (DateTime.UtcNow > nextStatusUpdateTime) ReportStatus(); if (sentCount == maxToSendPerMinute) { ReportSleeping(); Thread.Sleep(60000); //sleep 1 minute sentCount = 0; } } } ReportStatus(); }
public static void SendPublishRequestNotification( SmtpSettings smtpSettings, SiteSettings siteSettings, SiteUser submittingUser, SiteUser approvingUser, ContentWorkflow draftWorkflow, string publisherRoles, string contentUrl ) { if (string.IsNullOrEmpty(publisherRoles)) { publisherRoles = "Admins;Content Administrators;Content Publishers;"; } Module module = new Module(draftWorkflow.ModuleGuid); if (module == null) { return; } List<string> emailAddresses = SiteUser.GetEmailAddresses(siteSettings.SiteId, publisherRoles); //int queuedMessageCount = 0; CultureInfo defaultCulture = SiteUtils.GetDefaultUICulture(); string messageTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "PublishRequestNotification.config"); string messageSubject = ResourceHelper.GetMessageTemplate(defaultCulture, "PublishRequestNotificationSubject.config").Replace("{SiteName}", siteSettings.SiteName); foreach (string email in emailAddresses) { if (WebConfigSettings.EmailAddressesToExcludeFromAdminNotifications.IndexOf(email, StringComparison.InvariantCultureIgnoreCase) > -1) { continue; } if (!Email.IsValidEmailAddressSyntax(email)) { continue; } StringBuilder message = new StringBuilder(); message.Append(messageTemplate); message.Replace("{ModuleTitle}", draftWorkflow.ModuleTitle); message.Replace("{PublishRequestedDate}", draftWorkflow.RecentActionOn.ToShortDateString()); message.Replace("{SubmittedBy}", submittingUser.Name); message.Replace("{ApprovedBy}", approvingUser.Name); message.Replace("{ContentUrl}", contentUrl); Email.Send( smtpSettings, siteSettings.DefaultEmailFromAddress, siteSettings.DefaultFromEmailAlias, submittingUser.Email, email, string.Empty, string.Empty, messageSubject, message.ToString(), false, Email.PriorityNormal); } }
public EmailSenderServiceController(IOptions <SmtpSettings> smtpSettings) { _smtpSettings = smtpSettings.Value; }
public EmailProvider(SmtpSettings smtpSettings) { _smtpSettings = smtpSettings; }
private void btnSend_Click(object sender, EventArgs e) { //Page.Validate("Contact"); bool isValid = true; reqEmail.Validate(); if (!reqEmail.IsValid) { isValid = false; } regexEmail.Validate(); if (!regexEmail.IsValid) { isValid = false; } if ((isValid) && (edMessage.Text.Length > 0)) { if ((config.UseSpamBlocking) && (divCaptcha.Visible)) { if (!captcha.IsValid) { return; } } string subjectPrefix = config.SubjectPrefix; if (subjectPrefix.Length == 0) { subjectPrefix = Title; } StringBuilder message = new StringBuilder(); message.Append(txtName.Text + "<br />"); message.Append(txtEmail.Text + "<br /><br />"); message.Append(SiteUtils.ChangeRelativeUrlsToFullyQualifiedUrls(SiteUtils.GetNavigationSiteRoot(), WebUtils.GetSiteRoot(), edMessage.Text)); message.Append("<br /><br />"); if (config.AppendIPToMessageSetting) { message.Append("HTTP_USER_AGENT: " + Page.Request.ServerVariables["HTTP_USER_AGENT"] + "<br />"); message.Append("REMOTE_HOST: " + Page.Request.ServerVariables[WebConfigSettings.RemoteHostServerVariable] + "<br />"); message.Append("REMOTE_ADDR: " + SiteUtils.GetIP4Address() + "<br />"); message.Append("LOCAL_ADDR: " + Page.Request.ServerVariables["LOCAL_ADDR"] + "<br />"); } Module m = new Module(ModuleId); if ((config.KeepMessages) && (m.ModuleGuid != Guid.Empty)) { ContactFormMessage contact = new ContactFormMessage(); contact.ModuleGuid = m.ModuleGuid; contact.SiteGuid = siteSettings.SiteGuid; contact.Message = message.ToString(); contact.Subject = config.SubjectPrefix + ": " + txtSubject.Text; contact.UserName = txtName.Text; contact.Email = txtEmail.Text; contact.CreatedFromIpAddress = SiteUtils.GetIP4Address(); if (Request.IsAuthenticated) { SiteUser currentUser = SiteUtils.GetCurrentSiteUser(); if (currentUser != null) { contact.UserGuid = currentUser.UserGuid; } } contact.Save(); } string fromAddress = siteSettings.DefaultEmailFromAddress; if (config.UseInputAsFromAddress) { fromAddress = txtEmail.Text; } if ((config.EmailAddresses != null) && (config.EmailAddresses.Count > 0)) { SmtpSettings smtpSettings = SiteUtils.GetSmtpSettings(); if ((pnlToAddresses.Visible) && (ddToAddresses.SelectedIndex > -1)) { string to = config.EmailAddresses[ddToAddresses.SelectedIndex]; try { Email.SendEmail( smtpSettings, fromAddress, txtEmail.Text, to, string.Empty, config.EmailBccAddresses, subjectPrefix + ": " + this.txtSubject.Text, message.ToString(), true, "Normal"); } catch (Exception ex) { log.Error("error sending email from address was " + fromAddress + " to address was " + to, ex); } } else { foreach (string to in config.EmailAddresses) { try { Email.SendEmail( smtpSettings, fromAddress, txtEmail.Text, to, string.Empty, config.EmailBccAddresses, subjectPrefix + ": " + this.txtSubject.Text, message.ToString(), true, "Normal"); } catch (Exception ex) { log.Error("error sending email from address was " + fromAddress + " to address was " + to, ex); } } } } else { log.Info("contact form submission received but not sending email because notification email address is not configured."); } this.lblMessage.Text = ContactFormResources.ContactFormThankYouLabel; this.pnlSend.Visible = false; } else { if (edMessage.Text.Length == 0) { lblMessage.Text = ContactFormResources.ContactFormEmptyMessageWarning; } else { lblMessage.Text = "invalid"; } } btnSend.Text = ContactFormResources.ContactFormSendButtonLabel; btnSend.Enabled = true; }
void btnSendToList_Click(object sender, EventArgs e) { SaveLetter(); if (!LetterIsValidForSending()) { return; } if (letter.SendCompleteUtc > DateTime.MinValue) { return; } // TODO: implement approval process letter.ApprovedBy = currentUser.UserGuid; letter.IsApproved = true; string baseUrl = WebUtils.GetHostRoot(); if (WebConfigSettings.UseFoldersInsteadOfHostnamesForMultipleSites) { // in folder based sites the relative urls in the editor will already have the folder name // so we want to use just the raw site root not the navigation root baseUrl = WebUtils.GetSiteRoot(); } string content = SiteUtils.ChangeRelativeUrlsToFullyQualifiedUrls(baseUrl, WebUtils.GetSiteRoot(), letter.HtmlBody); letter.HtmlBody = content; SaveLetter(); letter.TrackSendClicked(); LetterSendTask letterSender = new LetterSendTask(); letterSender.SiteGuid = siteSettings.SiteGuid; letterSender.QueuedBy = currentUser.UserGuid; letterSender.LetterGuid = letter.LetterGuid; letterSender.UnsubscribeLinkText = Resource.NewsletterUnsubscribeLink; letterSender.ViewAsWebPageText = Resource.NewsletterViewAsWebPageLink; letterSender.UnsubscribeUrl = SiteRoot + "/eletter/Unsubscribe.aspx"; if (letterInfo.AllowArchiveView) { letterSender.WebPageUrl = SiteRoot + "/eletter/LetterView.aspx?l=" + letter.LetterInfoGuid.ToString() + "&letter=" + letter.LetterGuid.ToString(); } letterSender.NotificationFromEmail = siteSettings.DefaultEmailFromAddress; letterSender.NotifyOnCompletion = true; letterSender.NotificationToEmail = currentUser.Email; SmtpSettings smtpSettings = GetSmtpSettings(); letterSender.User = smtpSettings.User; letterSender.Password = smtpSettings.Password; letterSender.Server = smtpSettings.Server; letterSender.Port = smtpSettings.Port; letterSender.RequiresAuthentication = smtpSettings.RequiresAuthentication; letterSender.UseSsl = smtpSettings.UseSsl; letterSender.PreferredEncoding = smtpSettings.PreferredEncoding; letterSender.TaskUpdateFrequency = 65; letterSender.MaxToSendPerMinute = WebConfigSettings.NewsletterMaxToSendPerMinute; letterSender.QueueTask(); string redirectUrl = SiteRoot + "/eletter/SendProgress.aspx?l=" + letterInfoGuid.ToString() + "&letter=" + letterGuid.ToString() + "&t=" + letterSender.TaskGuid.ToString(); WebTaskManager.StartOrResumeTasks(); WebUtils.SetupRedirect(this, redirectUrl); }
public void SmtpSettings_AuthenticationSettings_IsInitialized() { var settings = new SmtpSettings(); settings.Authentication.Should().NotBeNull(); }
public DnsUpdater(SmtpSettings smtpSettings, HosteuropeSettings hosteuropeSettings, DomainSettings domainSettings) { this.smtpSettings = smtpSettings; this.hosteuropeSettings = hosteuropeSettings; this.domainSettings = domainSettings; }
public MailerManager(IOptions <SmtpSettings> smtpSetting) { _smtpSettings = smtpSetting.Value; }
public static SmtpSettings GetSmtpSettings(SiteSettings siteSettings) { SmtpSettings smtpSettings = new SmtpSettings(); if (WebConfigSettings.EnableSiteSettingsSmtpSettings) { if (siteSettings != null) { if (WebConfigSettings.UseLegacyCryptoHelper) { if (siteSettings.SMTPUser.Length > 0) { smtpSettings.User = CryptoHelper.Decrypt(siteSettings.SMTPUser); } if (siteSettings.SMTPPassword.Length > 0) { smtpSettings.Password = CryptoHelper.Decrypt(siteSettings.SMTPPassword); } } else { if (siteSettings.SMTPUser.Length > 0) { smtpSettings.User = SiteUtils.Decrypt(siteSettings.SMTPUser); } if (siteSettings.SMTPPassword.Length > 0) { smtpSettings.Password = SiteUtils.Decrypt(siteSettings.SMTPPassword); } } smtpSettings.Server = siteSettings.SMTPServer; smtpSettings.Port = siteSettings.SMTPPort; smtpSettings.RequiresAuthentication = siteSettings.SMTPRequiresAuthentication; smtpSettings.UseSsl = siteSettings.SMTPUseSsl; smtpSettings.PreferredEncoding = siteSettings.SMTPPreferredEncoding; } } else { return GetSmtpSettingsFromConfig(); } return smtpSettings; }
/// <summary> /// Envoi un courriel en format HTML /// </summary> /// <param name="tagFormater">L'objet de conversion des tags initialiser avec un compte</param> /// <param name="smtp">La configuration du serveur SMTP</param> /// <param name="recipients">La liste des récipients</param> /// <param name="subject">Le sujet du courriel</param> /// <param name="templateFile">Le modèle à utiliser pour le courriel</param> /// <param name="img">L'image du graphique</param> public void SendMailHTML(MailTagFormater tagFormater, SmtpSettings smtp, string recipients, string subject, string templateFile, VideotronAccount account) { // Les templates personnalisé sont plus fort que ceux de base (notion d'override) // Si le template n'existe pas, on prend le premier de la liste if (MailTemplates.FirstOrDefault(p => p.Name == templateFile) == null) { templateFile = MailTemplates.FirstOrDefault().Name; } subject = tagFormater.Convert(subject); StringBuilder template = new StringBuilder(tagFormater.Convert(MailTemplates.FirstOrDefault(p => p.Name == templateFile).GetContent())); SmtpClient client = new SmtpClient(smtp.Host, smtp.Port); client.Credentials = new NetworkCredential(smtp.Username, smtp.Password); MailMessage message = new MailMessage(); message.From = new MailAddress(smtp.SenderMail, smtp.Sender, System.Text.Encoding.UTF8); foreach (string address in recipients.Split(';')) { message.To.Add(new MailAddress(address)); } message.Subject = subject; switch (MailTemplates.FirstOrDefault(p => p.Name == templateFile).Encoding) { case MailTemplate.MailTemplateEncodingType.ASCII: message.SubjectEncoding = System.Text.Encoding.ASCII; message.BodyEncoding = System.Text.Encoding.ASCII; break; case MailTemplate.MailTemplateEncodingType.ISO8859: message.SubjectEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1"); message.BodyEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1"); break; default: message.SubjectEncoding = System.Text.Encoding.UTF8; message.BodyEncoding = System.Text.Encoding.UTF8; break; } // Modèle HTML if (MailTemplates.FirstOrDefault(p => p.Name == templateFile).IsHTML) { message.IsBodyHtml = true; AlternateView htmlView; // Embebbed image List <string> embeddedImageFile = new List <string>(); Match embeddedImage; string addedImage; do { embeddedImage = Regex.Match(template.ToString(), "src=\"(?<src>[^cid]+)\"", RegexOptions.IgnoreCase); if (embeddedImage.Success) { addedImage = System.IO.Path.Combine(MailTemplates.FirstOrDefault(p => p.Name == templateFile).Folder, embeddedImage.Groups["src"].Value); if (!File.Exists(addedImage)) { throw new FileNotFoundException(addedImage); } embeddedImageFile.Add(addedImage); template.Replace(String.Format("{0}", embeddedImage.Groups["src"].Value), String.Format("cid:img{0}", embeddedImageFile.Count)); } }while (embeddedImage.Success); // Insertion du graphique // Il faudrait le mettre dans MailTagFormater, mais c'est compliqué, pas le temps List <Tuple <int, int> > graphSize = new List <Tuple <int, int> >(); Match match = Regex.Match(template.ToString(), @"\[GRAPH(\((?<param>[^\)]*)?\))?\]", RegexOptions.IgnoreCase); int graphCount = 0; int delta = 0; while (match.Success) { int width = 430; int height = 230; Match paramMatch = Regex.Match(match.Groups["param"].Value, @"(?<method>[a-z]{3,})=(?<param>[^,]+)", RegexOptions.IgnoreCase); while (paramMatch.Success) { if (paramMatch.Groups["method"].Value.ToUpper() == "WIDTH") { width = Convert.ToInt32(paramMatch.Groups["param"].Value); } else if (paramMatch.Groups["method"].Value.ToUpper() == "HEIGHT") { height = Convert.ToInt32(paramMatch.Groups["param"].Value); } paramMatch = paramMatch.NextMatch(); } graphSize.Add(new Tuple <int, int>(width, height)); template.Remove(match.Index + delta, match.Length); string newValue = String.Format("<img src=\"cid:graph_{0}\" width=\"{1}\" height=\"{2}\" />", graphCount, width, height); template.Insert(match.Index + delta, newValue); if (match.Length > newValue.Length) { delta -= match.Length - newValue.Length; } else if (match.Length < newValue.Length) { delta += newValue.Length - match.Length; } graphCount++; match = match.NextMatch(); } htmlView = AlternateView.CreateAlternateViewFromString(template.ToString(), System.Text.Encoding.UTF8, "text/html"); for (int i = 0; i < graphSize.Count; i++) { System.Drawing.Image img; MemoryStream memoryGraph = new MemoryStream(); GraphFactory graphFactory = new GraphFactory(); ZedGraphControl graph = graphFactory.Generate(account.Username, new Period(account.PeriodStart, account.PeriodEnd), graphSize[i].Item1, graphSize[i].Item2); img = graph.GetImage(); img.Save(memoryGraph, System.Drawing.Imaging.ImageFormat.Jpeg); memoryGraph.Position = 0; htmlView.LinkedResources.Add(new LinkedResource(memoryGraph, MediaTypeNames.Image.Jpeg) { ContentId = String.Format("graph_{0}", i), TransferEncoding = TransferEncoding.Base64 }); } for (int i = 0; i < embeddedImageFile.Count; i++) { if (Regex.Match(embeddedImageFile[i], "(jpg|jpeg)$", RegexOptions.IgnoreCase).Success) { htmlView.LinkedResources.Add(new LinkedResource(embeddedImageFile[i], MediaTypeNames.Image.Jpeg) { ContentId = String.Format("img{0}", i + 1), TransferEncoding = TransferEncoding.Base64 }); } else if (Regex.Match(embeddedImageFile[i], "gif$", RegexOptions.IgnoreCase).Success) { htmlView.LinkedResources.Add(new LinkedResource(embeddedImageFile[i], MediaTypeNames.Image.Gif) { ContentId = String.Format("img{0}", i + 1), TransferEncoding = TransferEncoding.Base64 }); } else if (Regex.Match(embeddedImageFile[i], "tiff$", RegexOptions.IgnoreCase).Success) { htmlView.LinkedResources.Add(new LinkedResource(embeddedImageFile[i], MediaTypeNames.Image.Tiff) { ContentId = String.Format("img{0}", i + 1), TransferEncoding = TransferEncoding.Base64 }); } else { htmlView.LinkedResources.Add(new LinkedResource(embeddedImageFile[i]) { ContentId = String.Format("img{0}", i + 1), TransferEncoding = TransferEncoding.Base64 }); } } message.AlternateViews.Add(htmlView); } // Plain/Text else { message.Body = template.ToString(); } client.Send(message); message.Dispose(); }
internal static void UpdateSettings() { currentSettings = null; }
private void RunTask() { Letter letter = new Letter(this.letterGuid); if (letter.LetterGuid == Guid.Empty) { log.Error("LetterSendTask letter not found so ending."); ReportStatus(); return; } if (letter.SendCompleteUtc > DateTime.MinValue) { log.Error("LetterSendTask SendCompleteUtc already set so ending."); ReportStatus(); return; } if (letter.SendClickedUtc == DateTime.MinValue) { log.Error("LetterSendTask SendClickedUtc has an invalid value so ending."); ReportStatus(); return; } LetterInfo letterInfo = new LetterInfo(letter.LetterInfoGuid); SubscriberRepository subscriptions = new SubscriberRepository(); if (WebConfigSettings.NewsletterTestMode) { testMode = true; log.Info("using NewsletterTestMode=true in config so no real emails will be sent for newsletter " + letterInfo.Title); } // TODO: this could be a very large recordset if the list is very large // might be better to get a page at a time instead of all at once. List <LetterSubscriber> subscribers = subscriptions.GetSubscribersNotSentYet( letter.LetterGuid, letter.LetterInfoGuid); nextStatusUpdateTime = DateTime.UtcNow.AddSeconds(reportingFrequency); totalSubscribersToSend = subscribers.Count; if ((totalSubscribersToSend > 0) && (letter.SendStartedUtc == DateTime.MinValue)) { letter.TrackSendStarted(); } if (totalSubscribersToSend < 100) { testSleepMilliseconds = 3000; } if (totalSubscribersToSend > 300) { testSleepMilliseconds = 500; } if (totalSubscribersToSend > 500) { testSleepMilliseconds = 100; } SmtpSettings smtpSettings = new SmtpSettings(); smtpSettings.Password = password; smtpSettings.Port = port; smtpSettings.PreferredEncoding = preferredEncoding; smtpSettings.RequiresAuthentication = requiresAuthentication; smtpSettings.UseSsl = useSsl; smtpSettings.User = user; smtpSettings.Server = server; smtpSettings.AddBulkMailHeader = true; if (maxToSendPerMinute == 0) //not limit { foreach (LetterSubscriber subscriber in subscribers) { SendLetter(smtpSettings, letterInfo, letter, subscriber); subscribersSentSoFar += 1; if (DateTime.UtcNow > nextStatusUpdateTime) { ReportStatus(); } } } else { int sentCount = 0; foreach (LetterSubscriber subscriber in subscribers) { SendLetter(smtpSettings, letterInfo, letter, subscriber); subscribersSentSoFar += 1; sentCount += 1; if (DateTime.UtcNow > nextStatusUpdateTime) { ReportStatus(); } if (sentCount == maxToSendPerMinute) { ReportSleeping(); Thread.Sleep(60000); //sleep 1 minute sentCount = 0; } } } ReportStatus(); }
private void GetSmtpSettings() { SmtpSettings objSmtp = new SmtpSettings(); DataSet dsSmtp = objSmtp.GetSmtpSettings(); if (dsSmtp.Tables.Count > 0) { if (dsSmtp.Tables[0].Rows.Count > 0) { btnSmtpUpdate.Visible = true; btnSmtpSubmit.Visible = false; SMTPProperties objSmtpProp = new SMTPProperties(); SMTPSendEMail objEmail = new SMTPSendEMail(); if(dsSmtp.Tables[0].Rows[0][0]!= System.DBNull.Value) txtSmtpServer.Text = dsSmtp.Tables[0].Rows[0][0].ToString(); if (dsSmtp.Tables[0].Rows[0][1] != System.DBNull.Value) txtSmtpPort.Text = dsSmtp.Tables[0].Rows[0][1].ToString(); if (dsSmtp.Tables[0].Rows[0][2] != System.DBNull.Value) txtSmtpUserID.Text = dsSmtp.Tables[0].Rows[0][2].ToString(); if (dsSmtp.Tables[0].Rows[0][3] != System.DBNull.Value) txtSmtpPassword.Text = dsSmtp.Tables[0].Rows[0][3].ToString(); if (dsSmtp.Tables[0].Rows[0][4] != System.DBNull.Value) txtMailFrom.Text = dsSmtp.Tables[0].Rows[0][4].ToString(); if (dsSmtp.Tables[0].Rows[0][5] != System.DBNull.Value) txtMailTo.Text = dsSmtp.Tables[0].Rows[0][5].ToString(); if (dsSmtp.Tables[0].Rows[0][6] != System.DBNull.Value) chkIsSSL.Checked = bool.Parse(dsSmtp.Tables[0].Rows[0][6].ToString()); if (dsSmtp.Tables[0].Rows[0][7] != System.DBNull.Value) chkIsHTML.Checked = bool.Parse(dsSmtp.Tables[0].Rows[0][7].ToString()); char mailPriority='N'; if (dsSmtp.Tables[0].Rows[0][8] != System.DBNull.Value) mailPriority = char.Parse(dsSmtp.Tables[0].Rows[0][8].ToString()); switch (mailPriority) { case 'L': { ddlMailPriority.SelectedValue = "L"; break; } case 'H': { ddlMailPriority.SelectedValue = "H"; break; } case 'N': { ddlMailPriority.SelectedValue = "N"; break; } } } } else { btnSmtpSubmit.Visible = true; btnSmtpUpdate.Visible = false; } }
private void SendLetter( SmtpSettings smtpSettings, LetterInfo letterInfo, Letter letter, LetterSubscriber subscriber) { // TODO: use multi part email with both html and plain text body // instead of this either or approach? LetterSendLog mailLog = new LetterSendLog(); mailLog.EmailAddress = subscriber.EmailAddress; mailLog.LetterGuid = letter.LetterGuid; mailLog.UserGuid = subscriber.UserGuid; mailLog.SubscribeGuid = subscriber.SubscribeGuid; if (testMode) { Thread.Sleep(testSleepMilliseconds); // sleep 1 seconds per message to simulate } else { try { if (subscriber.UseHtml) { Email.Send( smtpSettings, letterInfo.FromAddress.Coalesce(notificationFromEmail), letterInfo.FromName.Coalesce(notificationFromAlias), letterInfo.ReplyToAddress.Coalesce(notificationFromAlias), subscriber.EmailAddress, string.Empty, string.Empty, letter.Subject, ReplaceHtmlTokens(letter.HtmlBody, subscriber, letterInfo), subscriber.UseHtml, "Normal"); } else { Email.Send( smtpSettings, letterInfo.FromAddress.Coalesce(notificationFromEmail), letterInfo.FromName.Coalesce(notificationFromAlias), letterInfo.ReplyToAddress.Coalesce(notificationFromEmail), subscriber.EmailAddress, string.Empty, string.Empty, letter.Subject, ReplaceTextTokens(letter.TextBody, subscriber, letterInfo), subscriber.UseHtml, "Normal"); } } catch (Exception ex) { // TODO: catch more specific exception(s) figure out what ones can be thrown here mailLog.ErrorOccurred = true; mailLog.ErrorMessage = ex.ToString(); log.Error(ex); } } mailLog.Save(); }
public static void SendApprovalRequestNotification( SmtpSettings smtpSettings, SiteSettings siteSettings, SiteUser submittingUser, ContentWorkflow draftWorkflow, string approvalRoles, string contentUrl ) { if (string.IsNullOrEmpty(approvalRoles)) { approvalRoles = "Admins;Content Administrators;Content Publishers;"; } List<string> emailAddresses = SiteUser.GetEmailAddresses(siteSettings.SiteId, approvalRoles); //int queuedMessageCount = 0; CultureInfo defaultCulture = SiteUtils.GetDefaultUICulture(); string messageTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "ApprovalRequestNotification.config"); string messageSubject = ResourceHelper.GetMessageTemplate(defaultCulture, "ApprovalRequestNotificationSubject.config").Replace("{SiteName}", siteSettings.SiteName); foreach (string email in emailAddresses) { if (WebConfigSettings.EmailAddressesToExcludeFromAdminNotifications.IndexOf(email, StringComparison.InvariantCultureIgnoreCase) > -1) { continue; } if (!Email.IsValidEmailAddressSyntax(email)) { continue; } StringBuilder message = new StringBuilder(); message.Append(messageTemplate); message.Replace("{ModuleTitle}", draftWorkflow.ModuleTitle); message.Replace("{ApprovalRequestedDate}", draftWorkflow.RecentActionOn.ToShortDateString()); message.Replace("{SubmittedBy}", submittingUser.Name); message.Replace("{ContentUrl}", contentUrl); if (!Email.IsValidEmailAddressSyntax(draftWorkflow.RecentActionByUserEmail)) { //invalid address log it log.Error("Failed to send workflow rejection message, invalid recipient email " + draftWorkflow.RecentActionByUserEmail + " message was " + message.ToString()); return; } //EmailMessageTask messageTask = new EmailMessageTask(smtpSettings); //messageTask.SiteGuid = siteSettings.SiteGuid; //messageTask.EmailFrom = siteSettings.DefaultEmailFromAddress; //messageTask.EmailReplyTo = submittingUser.Email; //messageTask.EmailTo = email; //messageTask.Subject = messageSubject; //messageTask.TextBody = message.ToString(); //messageTask.QueueTask(); //queuedMessageCount += 1; Email.Send( smtpSettings, siteSettings.DefaultEmailFromAddress, siteSettings.DefaultFromEmailAlias, submittingUser.Email, email, string.Empty, string.Empty, messageSubject, message.ToString(), false, Email.PriorityNormal); } //if (queuedMessageCount > 0) { WebTaskManager.StartOrResumeTasks(); } }
public EmailController(IMailTransport mailTransport, SmtpSettings settings) { _mailTransport = mailTransport; _settings = settings; }
private void SendEmailMessage(string Message) { try { SmtpSettings objSmtp = new SmtpSettings(); DataSet dsSmtp = objSmtp.GetSmtpSettings(); if (dsSmtp.Tables.Count > 0) { if (dsSmtp.Tables[0].Rows.Count > 0) { SMTPProperties objSmtpProp = new SMTPProperties(); SMTPSendEMail objEmail = new SMTPSendEMail(); objSmtpProp.Server = dsSmtp.Tables[0].Rows[0][0].ToString(); objSmtpProp.Port = int.Parse(dsSmtp.Tables[0].Rows[0][1].ToString()); objSmtpProp.UserName = dsSmtp.Tables[0].Rows[0][2].ToString(); objSmtpProp.PassWord = dsSmtp.Tables[0].Rows[0][3].ToString(); if (txtEmailFrom.Text != "") objSmtpProp.MailFrom = txtEmailFrom.Text; else objSmtpProp.MailFrom = dsSmtp.Tables[0].Rows[0][4].ToString(); objSmtpProp.MailTo = txtEmailTo.Text; objSmtpProp.IsSSL = bool.Parse(dsSmtp.Tables[0].Rows[0][6].ToString()); objSmtpProp.IsHTML = bool.Parse(dsSmtp.Tables[0].Rows[0][7].ToString()); char mailPriority = char.Parse(dsSmtp.Tables[0].Rows[0][8].ToString()); switch (mailPriority) { case 'L': { objSmtpProp.MailPriority = SMTPProperties.Priority.Low; break; } case 'H': { objSmtpProp.MailPriority = SMTPProperties.Priority.High; break; } case 'N': { objSmtpProp.MailPriority = SMTPProperties.Priority.Normal; break; } } if (txtEmailSubject.Text != "") objSmtpProp.MailSubject = txtEmailSubject.Text; else objSmtpProp.MailSubject = "Call Log"; if (txtEmailMessage.Text != "") objSmtpProp.MailMessage = txtEmailMessage.Text + "<br/>" + Message; else objSmtpProp.MailMessage = Message; MailResponse objMailResp = objEmail.SendEmail(objSmtpProp); string str = "alert('" + objMailResp.StatusMessage + "');"; ScriptManager.RegisterStartupScript(imgBtnSendEmail, typeof(Page), "alert", str, true); } } } catch (Exception ex) { objNLog.Error("Error : " + ex.Message); } }
public static bool Send( SmtpSettings smtpSettings, string from, string fromAlias, string replyTo, string to, string cc, string bcc, string subject, string messageBody, bool html, string priority, List<Attachment> attachments) { if (to == "*****@*****.**") { return false; } //demo site if ((ConfigurationManager.AppSettings["DisableSmtp"] != null) && (ConfigurationManager.AppSettings["DisableSmtp"] == "true")) { log.Info("Not Sending email because DisableSmtp is true in config."); return false; } if ((smtpSettings == null) || (!smtpSettings.IsValid)) { log.Error("Invalid smtp settings detected in SendEmail "); return false; } if (debugLog) log.DebugFormat("In SendEmailNormal({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7})", from, to, cc, bcc, subject, messageBody, html, priority); using (MailMessage mail = new MailMessage()) { SetMessageEncoding(smtpSettings, mail); MailAddress fromAddress; try { if (fromAlias.Length > 0) { fromAddress = new MailAddress(from, fromAlias); } else { fromAddress = new MailAddress(from); } } catch (ArgumentException) { log.Error("invalid from address " + from); log.Info("no valid from address was provided so not sending message " + messageBody); return false; } catch (FormatException) { log.Error("invalid from address " + from); log.Info("no valid from address was provided so not sending message " + messageBody); return false; } mail.From = fromAddress; List<string> toAddresses = to.Replace(";", ",").SplitOnChar(','); foreach (string toAddress in toAddresses) { try { MailAddress a = new MailAddress(toAddress); mail.To.Add(a); } catch (ArgumentException) { log.Error("ignoring invalid to address " + toAddress); } catch (FormatException) { log.Error("ignoring invalid to address " + toAddress); } } if (mail.To.Count == 0) { log.Error("no valid to address was provided so not sending message " + messageBody); return false; } if (replyTo.Length > 0) { try { MailAddress replyAddress = new MailAddress(replyTo); mail.ReplyTo = replyAddress; } catch (ArgumentException) { log.Error("ignoring invalid replyto address " + replyTo); } catch (FormatException) { log.Error("ignoring invalid replyto address " + replyTo); } } if (cc.Length > 0) { List<string> ccAddresses = cc.Replace(";", ",").SplitOnChar(','); foreach (string ccAddress in ccAddresses) { try { MailAddress a = new MailAddress(ccAddress); mail.CC.Add(a); } catch (ArgumentException) { log.Error("ignoring invalid cc address " + ccAddress); } catch (FormatException) { log.Error("ignoring invalid cc address " + ccAddress); } } } if (bcc.Length > 0) { List<string> bccAddresses = bcc.Replace(";", ",").SplitOnChar(','); foreach (string bccAddress in bccAddresses) { try { MailAddress a = new MailAddress(bccAddress); mail.Bcc.Add(a); } catch (ArgumentException) { log.Error("invalid bcc address " + bccAddress); } catch (FormatException) { log.Error("invalid bcc address " + bccAddress); } } } mail.Subject = subject.RemoveLineBreaks(); switch (priority) { case PriorityHigh: mail.Priority = MailPriority.High; break; case PriorityLow: mail.Priority = MailPriority.Low; break; case PriorityNormal: default: mail.Priority = MailPriority.Normal; break; } if (html) { mail.IsBodyHtml = true; // this char can reportedly cause problems in some email clients so replace it if it exists mail.Body = messageBody.Replace("\xA0", " "); } else { mail.Body = messageBody; } // add attachments if there are any if (attachments != null) { foreach (Attachment a in attachments) { mail.Attachments.Add(a); } } if (smtpSettings.AddBulkMailHeader) { mail.Headers.Add("Precedence", "bulk"); } return Send(smtpSettings, mail); }// end using MailMessage }
public static void SendApprovalRequestNotification( SmtpSettings smtpSettings, SiteSettings siteSettings, SiteUser submittingUser, ContentWorkflow draftWorkflow, string approvalRoles, string contentUrl ) { if (string.IsNullOrEmpty(approvalRoles)) { approvalRoles = "Admins;Content Administrators;Content Publishers;"; } List <string> emailAddresses = SiteUser.GetEmailAddresses(siteSettings.SiteId, approvalRoles); //int queuedMessageCount = 0; CultureInfo defaultCulture = SiteUtils.GetDefaultUICulture(); string messageTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "ApprovalRequestNotification.config"); string messageSubject = ResourceHelper.GetMessageTemplate(defaultCulture, "ApprovalRequestNotificationSubject.config").Replace("{SiteName}", siteSettings.SiteName); foreach (string email in emailAddresses) { if (WebConfigSettings.EmailAddressesToExcludeFromAdminNotifications.IndexOf(email, StringComparison.InvariantCultureIgnoreCase) > -1) { continue; } if (!Email.IsValidEmailAddressSyntax(email)) { continue; } StringBuilder message = new StringBuilder(); message.Append(messageTemplate); message.Replace("{ModuleTitle}", draftWorkflow.ModuleTitle); message.Replace("{ApprovalRequestedDate}", draftWorkflow.RecentActionOn.ToShortDateString()); message.Replace("{SubmittedBy}", submittingUser.Name); message.Replace("{ContentUrl}", contentUrl); if (!Email.IsValidEmailAddressSyntax(draftWorkflow.RecentActionByUserEmail)) { //invalid address log it log.Error("Failed to send workflow rejection message, invalid recipient email " + draftWorkflow.RecentActionByUserEmail + " message was " + message.ToString()); return; } //EmailMessageTask messageTask = new EmailMessageTask(smtpSettings); //messageTask.SiteGuid = siteSettings.SiteGuid; //messageTask.EmailFrom = siteSettings.DefaultEmailFromAddress; //messageTask.EmailReplyTo = submittingUser.Email; //messageTask.EmailTo = email; //messageTask.Subject = messageSubject; //messageTask.TextBody = message.ToString(); //messageTask.QueueTask(); //queuedMessageCount += 1; Email.Send( smtpSettings, siteSettings.DefaultEmailFromAddress, siteSettings.DefaultFromEmailAlias, submittingUser.Email, email, string.Empty, string.Empty, messageSubject, message.ToString(), false, Email.PriorityNormal); } //if (queuedMessageCount > 0) { WebTaskManager.StartOrResumeTasks(); } }
public static bool Send(SmtpSettings smtpSettings, MailMessage message) { if (message.To.ToString() == "*****@*****.**") { return false; } //demo site string globalBcc = GetGlobalBccAddress(); if (globalBcc.Length > 0) { MailAddress bcc = new MailAddress(globalBcc); message.Bcc.Add(bcc); } int timeoutMilliseconds = ConfigHelper.GetIntProperty("SMTPTimeoutInMilliseconds", 15000); SmtpClient smtpClient = new SmtpClient(smtpSettings.Server, smtpSettings.Port); smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.EnableSsl = smtpSettings.UseSsl; smtpClient.Timeout = timeoutMilliseconds; if (smtpSettings.RequiresAuthentication) { NetworkCredential smtpCredential = new NetworkCredential( smtpSettings.User, smtpSettings.Password); CredentialCache myCache = new CredentialCache(); myCache.Add(smtpSettings.Server, smtpSettings.Port, "LOGIN", smtpCredential); smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = myCache; } else { //aded 2010-01-22 JA smtpClient.UseDefaultCredentials = true; } try { smtpClient.Send(message); //log.Debug("Sent Message: " + subject); //log.Info("Sent Message: " + subject); bool logEmail = ConfigHelper.GetBoolProperty("LogAllEmailsWithSubject", false); if (logEmail) { log.Info("Sent message " + message.Subject + " to " + message.To[0].Address); } return true; } catch (System.Net.Mail.SmtpException ex) { //log.Error("error sending email to " + to + " from " + from, ex); log.Error("error sending email to " + message.To.ToString() + " from " + message.From.ToString() + ", will retry", ex); return RetrySend(message, smtpClient, ex); } catch (WebException ex) { log.Error("error sending email to " + message.To.ToString() + " from " + message.From.ToString() + ", message was: " + message.Body, ex); return false; } catch (SocketException ex) { log.Error("error sending email to " + message.To.ToString() + " from " + message.From.ToString() + ", message was: " + message.Body, ex); return false; } catch (InvalidOperationException ex) { log.Error("error sending email to " + message.To.ToString() + " from " + message.From.ToString() + ", message was: " + message.Body, ex); return false; } catch (FormatException ex) { log.Error("error sending email to " + message.To.ToString() + " from " + message.From.ToString() + ", message was: " + message.Body, ex); return false; } }
public virtual Task <bool> SendMailAsync(MailMessage mailMessage, SmtpSettings smtpSettings) { SetSmtpSettings(smtpSettings); return(SendMailAsync(mailMessage)); }
public static void SendEmail( SmtpSettings smtpSettings, string from, string replyTo, string to, string cc, string bcc, string subject, string messageBody, bool html, string priority) { if (to == "*****@*****.**") { return; } //demo site if ((ConfigurationManager.AppSettings["DisableSmtp"] != null) && (ConfigurationManager.AppSettings["DisableSmtp"] == "true")) { log.Info("Not Sending email because DisableSmtp is true in config."); return; } if ((smtpSettings == null) || (!smtpSettings.IsValid)) { log.Error("Invalid smtp settings detected in SendEmail "); return; } if (replyTo.Length > 0) { SendEmailNormal( smtpSettings, from, replyTo, to, cc, bcc, subject, messageBody, html, priority); return; } SendEmail( smtpSettings, from, to, cc, bcc, subject, messageBody, html, priority); }
public MailMessage BuildMailMessage(SmtpSettings settings, string recipientList, string subject, string message) { var recipients = GetEmailList(recipientList); return(BuildMailMessage(settings, recipients, subject, message)); }
/// <summary> /// This method uses the built in .NET classes to send mail. /// </summary> /// <param name="smtpSettings"></param> /// <param name="from"></param> /// <param name="replyTo"></param> /// <param name="to"></param> /// <param name="cc"></param> /// <param name="bcc"></param> /// <param name="subject"></param> /// <param name="messageBody"></param> /// <param name="html"></param> /// <param name="priority"></param> public static void SendEmailNormal( SmtpSettings smtpSettings, string from, string replyTo, string to, string cc, string bcc, string subject, string messageBody, bool html, string priority) { if (to == "*****@*****.**") { return; } //demo site if ((ConfigurationManager.AppSettings["DisableSmtp"] != null) && (ConfigurationManager.AppSettings["DisableSmtp"] == "true")) { log.Info("Not Sending email because DisableSmtp is true in config."); return; } string[] attachmentPaths = new string[0]; string[] attachmentNames = new string[0]; SendEmailNormal( smtpSettings, from, replyTo, to, cc, bcc, subject, messageBody, html, priority, attachmentPaths, attachmentNames); }
public ISmtpClient CreateClient(SmtpSettings settings) { Settings = settings; return(Client); }
/// <summary> /// This method uses the built in .NET classes to send mail. /// </summary> /// <param name="smtpSettings"></param> /// <param name="from"></param> /// <param name="replyTo"></param> /// <param name="to"></param> /// <param name="cc"></param> /// <param name="bcc"></param> /// <param name="subject"></param> /// <param name="messageBody"></param> /// <param name="html"></param> /// <param name="priority"></param> /// <param name="attachmentPaths"></param> /// <param name="attachmentNames"></param> public static void SendEmailNormal( SmtpSettings smtpSettings, string from, string replyTo, string to, string cc, string bcc, string subject, string messageBody, bool html, string priority, string[] attachmentPaths, string[] attachmentNames) { if (to == "*****@*****.**") { return; } //demo site Send(smtpSettings, from, replyTo, to, cc, bcc, subject, messageBody, html, priority, attachmentPaths, attachmentNames); }
private static SmtpSettings GetSmtpSettingsFromConfig() { SmtpSettings smtpSettings = new SmtpSettings(); if (ConfigurationManager.AppSettings["SMTPUser"] != null) { smtpSettings.User = ConfigurationManager.AppSettings["SMTPUser"]; } if (ConfigurationManager.AppSettings["SMTPPassword"] != null) { smtpSettings.Password = ConfigurationManager.AppSettings["SMTPPassword"]; } if (ConfigurationManager.AppSettings["SMTPServer"] != null) { smtpSettings.Server = ConfigurationManager.AppSettings["SMTPServer"]; } smtpSettings.Port = ConfigHelper.GetIntProperty("SMTPPort", 25); bool byPassContext = true; smtpSettings.RequiresAuthentication = ConfigHelper.GetBoolProperty("SMTPRequiresAuthentication", false, byPassContext); ; smtpSettings.UseSsl = ConfigHelper.GetBoolProperty("SMTPUseSsl", false, byPassContext); if ( (ConfigurationManager.AppSettings["SmtpPreferredEncoding"] != null) && (ConfigurationManager.AppSettings["SmtpPreferredEncoding"].Length > 0) ) { smtpSettings.PreferredEncoding = ConfigurationManager.AppSettings["SmtpPreferredEncoding"]; } return smtpSettings; }
public static void SetMessageEncoding(SmtpSettings smtpSettings, MailMessage mail) { //http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx if (smtpSettings.PreferredEncoding.Length > 0) { switch (smtpSettings.PreferredEncoding) { case "ascii": case "us-ascii": // do nothing since this is the default break; case "utf32": case "utf-32": mail.BodyEncoding = Encoding.UTF32; mail.SubjectEncoding = Encoding.UTF32; break; case "unicode": mail.BodyEncoding = Encoding.Unicode; mail.SubjectEncoding = Encoding.Unicode; break; case "utf8": case "utf-8": mail.BodyEncoding = Encoding.UTF8; mail.SubjectEncoding = Encoding.UTF8; break; default: try { mail.BodyEncoding = Encoding.GetEncoding(smtpSettings.PreferredEncoding); mail.SubjectEncoding = Encoding.GetEncoding(smtpSettings.PreferredEncoding); } catch (ArgumentException ex) { log.Error(ex); } break; } } }
private static SmtpSettings GetSettings() { if (currentSettings == null) { using (var dw = Application.Current.CreateDataWorkspace()) { MailSettings settings = dw.ApplicationData.MailSettingsSet.FirstOrDefault(); if (settings == null) return null; currentSettings = new SmtpSettings(settings.SmtpServer, settings.Username, settings.Password, settings.SenderAddress, settings.Port); } } return currentSettings; }
/// <summary> /// This method uses the built in .NET classes to send mail. /// </summary> /// <param name="smtpSettings"></param> /// <param name="from"></param> /// <param name="replyTo"></param> /// <param name="to"></param> /// <param name="cc"></param> /// <param name="bcc"></param> /// <param name="subject"></param> /// <param name="messageBody"></param> /// <param name="html"></param> /// <param name="priority"></param> /// <param name="attachmentPaths"></param> /// <param name="attachmentNames"></param> public static bool Send( SmtpSettings smtpSettings, string from, string replyTo, string to, string cc, string bcc, string subject, string messageBody, bool html, string priority, string[] attachmentPaths, string[] attachmentNames) { if (to == "*****@*****.**") { return false; } //demo site string fromAlias = string.Empty; return Send( smtpSettings, from, fromAlias, replyTo, to, cc, bcc, subject, messageBody, html, priority, attachmentPaths, attachmentNames); }
public EmailService(IOptions <SmtpSettings> smtpSettingsOptions) { _smtpSettings = smtpSettingsOptions.Value; }
public static void SendPublishRejectionNotification( SmtpSettings smtpSettings, SiteSettings siteSettings, SiteUser rejectingUser, SiteUser draftSubmissionUser, ContentWorkflow rejectedWorkflow, string rejectionReason ) { CultureInfo defaultCulture = SiteUtils.GetDefaultUICulture(); string messageTemplate = String.Empty; string messageSubject = String.Empty; List<string> messageRecipients = new List<string>(); if (Email.IsValidEmailAddressSyntax(rejectedWorkflow.RecentActionByUserEmail)) { messageRecipients.Add(rejectedWorkflow.RecentActionByUserEmail); } messageTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "PublishRequestRejectionNotification.config"); messageSubject = ResourceHelper.GetMessageTemplate(defaultCulture, "PublishRequestRejectionNotificationSubject.config").Replace("{SiteName}", siteSettings.SiteName); if (Email.IsValidEmailAddressSyntax(draftSubmissionUser.LoweredEmail)) { messageRecipients.Add(draftSubmissionUser.LoweredEmail); } StringBuilder message = new StringBuilder(); message.Append(messageTemplate); message.Replace("{ModuleTitle}", rejectedWorkflow.ModuleTitle); message.Replace("{PublishRequestedDate}", rejectedWorkflow.RecentActionOn.ToShortDateString()); message.Replace("{RejectionReason}", rejectionReason); message.Replace("{RejectedBy}", rejectingUser.Name); if (messageRecipients.Count < 1) { //no valid addresses -- log it log.Error("Failed to send workflow publish rejection message, no valid recipient email " + rejectedWorkflow.RecentActionByUserEmail + ", " + draftSubmissionUser.LoweredEmail + " message was " + message.ToString()); return; } foreach (string recipient in messageRecipients) { Email.Send( smtpSettings, siteSettings.DefaultEmailFromAddress, siteSettings.DefaultFromEmailAlias, rejectingUser.Email, recipient, string.Empty, string.Empty, messageSubject, message.ToString(), false, Email.PriorityNormal); } }
public static void SendPublishRequestNotification( SmtpSettings smtpSettings, SiteSettings siteSettings, SiteUser submittingUser, SiteUser approvingUser, ContentWorkflow draftWorkflow, string publisherRoles, string contentUrl ) { if (string.IsNullOrEmpty(publisherRoles)) { publisherRoles = "Admins;Content Administrators;Content Publishers;"; } Module module = new Module(draftWorkflow.ModuleGuid); if (module == null) { return; } List <string> emailAddresses = SiteUser.GetEmailAddresses(siteSettings.SiteId, publisherRoles); //int queuedMessageCount = 0; CultureInfo defaultCulture = SiteUtils.GetDefaultUICulture(); string messageTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "PublishRequestNotification.config"); string messageSubject = ResourceHelper.GetMessageTemplate(defaultCulture, "PublishRequestNotificationSubject.config").Replace("{SiteName}", siteSettings.SiteName); foreach (string email in emailAddresses) { if (WebConfigSettings.EmailAddressesToExcludeFromAdminNotifications.IndexOf(email, StringComparison.InvariantCultureIgnoreCase) > -1) { continue; } if (!Email.IsValidEmailAddressSyntax(email)) { continue; } StringBuilder message = new StringBuilder(); message.Append(messageTemplate); message.Replace("{ModuleTitle}", draftWorkflow.ModuleTitle); message.Replace("{PublishRequestedDate}", draftWorkflow.RecentActionOn.ToShortDateString()); message.Replace("{SubmittedBy}", submittingUser.Name); message.Replace("{ApprovedBy}", approvingUser.Name); message.Replace("{ContentUrl}", contentUrl); Email.Send( smtpSettings, siteSettings.DefaultEmailFromAddress, siteSettings.DefaultFromEmailAlias, submittingUser.Email, email, string.Empty, string.Empty, messageSubject, message.ToString(), false, Email.PriorityNormal); } }
public static void SendRejectionNotification( SmtpSettings smtpSettings, SiteSettings siteSettings, SiteUser rejectingUser, ContentWorkflow rejectedWorkflow, string rejectionReason ) { //EmailMessageTask messageTask = new EmailMessageTask(smtpSettings); //messageTask.SiteGuid = siteSettings.SiteGuid; //messageTask.EmailFrom = siteSettings.DefaultEmailFromAddress; //messageTask.EmailFromAlias = siteSettings.DefaultFromEmailAlias; //messageTask.EmailReplyTo = rejectingUser.Email; //messageTask.EmailTo = rejectedWorkflow.RecentActionByUserEmail; CultureInfo defaultCulture = SiteUtils.GetDefaultUICulture(); //messageTask.Subject = ResourceHelper.GetMessageTemplate(defaultCulture, "ApprovalRequestRejectionNotificationSubject.config").Replace("{SiteName}", siteSettings.SiteName); StringBuilder message = new StringBuilder(); message.Append(ResourceHelper.GetMessageTemplate(defaultCulture, "ApprovalRequestRejectionNotification.config")); message.Replace("{ModuleTitle}", rejectedWorkflow.ModuleTitle); message.Replace("{ApprovalRequestedDate}", rejectedWorkflow.RecentActionOn.ToShortDateString()); message.Replace("{RejectionReason}", rejectionReason); message.Replace("{RejectedBy}", rejectingUser.Name); if (!Email.IsValidEmailAddressSyntax(rejectedWorkflow.RecentActionByUserEmail)) { //invalid address log it log.Error("Failed to send workflow rejection message, invalid recipient email " + rejectedWorkflow.RecentActionByUserEmail + " message was " + message.ToString()); return; } //messageTask.TextBody = message.ToString(); //messageTask.QueueTask(); //WebTaskManager.StartOrResumeTasks(); Email.Send( smtpSettings, siteSettings.DefaultEmailFromAddress, siteSettings.DefaultFromEmailAlias, rejectingUser.Email, rejectedWorkflow.RecentActionByUserEmail, string.Empty, string.Empty, ResourceHelper.GetMessageTemplate(defaultCulture, "ApprovalRequestRejectionNotificationSubject.config").Replace("{SiteName}", siteSettings.SiteName), message.ToString(), false, Email.PriorityNormal); }
public UserController(IOptions <SmtpSettings> settings) { SmtpSettings = settings.Value; }
public EmailProvider(IOptions <SmtpSettings> settings, IQueueProvider queueProvider) { _settings = settings.Value; _queueProvider = queueProvider; }
public static void ApplyPartnerWhiteLableSettings() { if (!TenantExtra.Enterprise && !TenantExtra.Hosted) { return; } var firstVisit = CompanyWhiteLabelSettings.Instance.IsDefault && AdditionalWhiteLabelSettings.Instance.IsDefault && MailWhiteLabelSettings.Instance.IsDefault; try { var partnerdataStorage = StorageFactory.GetStorage(Tenant.DEFAULT_TENANT.ToString(CultureInfo.InvariantCulture), "static_partnerdata"); if (partnerdataStorage == null) { return; } if (!partnerdataStorage.IsFile(JsonDataFilePath)) { return; } var stream = partnerdataStorage.GetReadStream(JsonDataFilePath); JObject jsonObject; using (var reader = new StreamReader(stream)) { jsonObject = JObject.Parse(reader.ReadToEnd()); } if (jsonObject == null) { return; } var companySettings = JsonConvert.DeserializeObject <CompanyWhiteLabelSettings>(jsonObject["CompanyWhiteLabelSettings"].ToString()); var additionalSettings = JsonConvert.DeserializeObject <AdditionalWhiteLabelSettings>(jsonObject["AdditionalWhiteLabelSettings"].ToString()); var mailSettings = JsonConvert.DeserializeObject <MailWhiteLabelSettings>(jsonObject["MailWhiteLabelSettings"].ToString()); var tenantSettings = JsonConvert.DeserializeObject <TenantWhiteLabelSettings>(jsonObject["TenantWhiteLabelSettings"].ToString()); var smtpSettingsStr = jsonObject["SmtpSettings"].ToString(); var defaultCultureName = jsonObject["DefaultCulture"].ToString(); SettingsManager.Instance.SaveSettings(companySettings, Tenant.DEFAULT_TENANT); SettingsManager.Instance.SaveSettings(additionalSettings, Tenant.DEFAULT_TENANT); SettingsManager.Instance.SaveSettings(mailSettings, Tenant.DEFAULT_TENANT); SettingsManager.Instance.SaveSettings(tenantSettings, Tenant.DEFAULT_TENANT); if (!String.IsNullOrEmpty(smtpSettingsStr)) { try { SmtpSettings.Deserialize(smtpSettingsStr); // try deserialize SmtpSettings object CoreContext.Configuration.SaveSetting("SmtpSettings", smtpSettingsStr); } catch (Exception e) { Log.Error(e.Message, e); } } if (!String.IsNullOrEmpty(defaultCultureName)) { var defaultCulture = CultureInfo.GetCultureInfo(defaultCultureName); if (SetupInfo.EnabledCultures.Find(culture => String.Equals(culture.Name, defaultCulture.Name, StringComparison.InvariantCultureIgnoreCase)) != null) { var tenant = CoreContext.TenantManager.GetCurrentTenant(); tenant.Language = defaultCulture.Name; CoreContext.TenantManager.SaveTenant(tenant); } } var logoImages = partnerdataStorage.ListFiles(String.Empty, LogoPattern, false); if (!logoImages.Any()) { MakeLogoFiles(partnerdataStorage, jsonObject); } if (!firstVisit) { return; } var tenantInfoSettings = SettingsManager.Instance.LoadSettings <TenantInfoSettings>(TenantProvider.CurrentTenantID); tenantInfoSettings.RestoreDefaultTenantName(); } catch (Exception e) { Log.Error(e.Message, e); } }
public static void NotifySubscribers( Forum forum, ForumThread thread, Module module, SiteUser siteUser, SiteSettings siteSettings, ForumConfiguration config, string siteRoot, int pageId, int pageNumber, CultureInfo defaultCulture, SmtpSettings smtpSettings, bool notifyModeratorOnly) { string threadViewUrl; if (ForumConfiguration.CombineUrlParams) { threadViewUrl = siteRoot + "/Forums/Thread.aspx?pageid=" + pageId.ToInvariantString() + "&t=" + thread.ThreadId.ToInvariantString() + "~" + pageNumber.ToInvariantString() + "#post" + thread.PostId.ToInvariantString(); } else { threadViewUrl = siteRoot + "/Forums/Thread.aspx?thread=" + thread.ThreadId.ToInvariantString() + "&mid=" + module.ModuleId.ToInvariantString() + "&pageid=" + pageId.ToInvariantString() + "&ItemID=" + forum.ItemId.ToInvariantString() + "&pagenumber=" + pageNumber.ToInvariantString() + "#post" + thread.PostId.ToInvariantString(); } ForumNotificationInfo notificationInfo = new ForumNotificationInfo(); notificationInfo.ThreadId = thread.ThreadId; notificationInfo.PostId = thread.PostId; notificationInfo.SubjectTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "ForumNotificationEmailSubject.config"); if (config.IncludePostBodyInNotification) { string postedBy = string.Empty; if (siteUser != null) { string sigFormat = ResourceHelper.GetResourceString("ForumResources", "PostedByFormat", defaultCulture, true); postedBy = string.Format(CultureInfo.InvariantCulture, sigFormat, siteUser.Name) + "\r\n\r\n"; ; } string bodyWithFullLinks = SiteUtils.ChangeRelativeLinksToFullyQualifiedLinks( siteRoot, thread.PostMessage); List<string> urls = SiteUtils.ExtractUrls(bodyWithFullLinks); notificationInfo.MessageBody = System.Web.HttpUtility.HtmlDecode(SecurityHelper.RemoveMarkup(thread.PostMessage)); if (urls.Count > 0) { notificationInfo.MessageBody += "\r\n" + ResourceHelper.GetResourceString("ForumResources", "PostedLinks", defaultCulture, true); foreach (string s in urls) { notificationInfo.MessageBody += "\r\n" + s.Replace("&", "&"); // html decode url params } notificationInfo.MessageBody += "\r\n\r\n"; } notificationInfo.MessageBody += "\r\n\r\n" + postedBy; } notificationInfo.BodyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "ForumNotificationEmail.config"); notificationInfo.ForumOnlyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "ForumNotificationEmail-ForumOnly.config"); notificationInfo.ThreadOnlyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "ForumNotificationEmail-ThreadOnly.config"); notificationInfo.ModeratorTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "ForumModeratorNotificationEmail.config"); notificationInfo.FromEmail = siteSettings.DefaultEmailFromAddress; notificationInfo.FromAlias = siteSettings.DefaultFromEmailAlias; if (config.OverrideNotificationFromAddress.Length > 0) { notificationInfo.FromEmail = config.OverrideNotificationFromAddress; notificationInfo.FromAlias = config.OverrideNotificationFromAlias; } notificationInfo.SiteName = siteSettings.SiteName; notificationInfo.ModuleName = module.ModuleTitle; notificationInfo.ForumName = forum.Title; notificationInfo.Subject = SecurityHelper.RemoveMarkup(thread.PostSubject); notificationInfo.MessageLink = threadViewUrl; notificationInfo.UnsubscribeForumThreadLink = siteRoot + "/Forums/UnsubscribeThread.aspx"; notificationInfo.UnsubscribeForumLink = siteRoot + "/Forums/UnsubscribeForum.aspx"; notificationInfo.SmtpSettings = smtpSettings; if (notifyModeratorOnly) { // just send notification to moderator List<string> moderatorsEmails = forum.ModeratorNotifyEmail.SplitOnChar(','); if (moderatorsEmails.Count > 0) { notificationInfo.ModeratorEmailAddresses = moderatorsEmails; ThreadPool.QueueUserWorkItem(new WaitCallback(ForumNotification.SendForumModeratorNotificationEmail), notificationInfo); } } else { // Send notification to subscribers DataSet dsThreadSubscribers = thread.GetThreadSubscribers(config.IncludeCurrentUserInNotifications); notificationInfo.Subscribers = dsThreadSubscribers; ThreadPool.QueueUserWorkItem(new WaitCallback(ForumNotification.SendForumNotificationEmail), notificationInfo); } }
public SmtpNoteEmailService(IOptions <SmtpSettings> settings, ILogger <SmtpNoteEmailService> logger) { _settings = settings.Value; _logger = logger; }
public void SendMail(string[] args) { CDOSmtpMessage smtpMessage = new CDOSmtpMessage(Extensions.LoadCDOMessage(args.GetRequiredValue(0))); // // Use SmtpRoute to get some free code coverage/easy test // SmtpMessageForwarder route = new SmtpMessageForwarder(); SmtpSettings settings = new SmtpSettings() { Server = args.GetRequiredValue(1), Port = args.GetOptionalValue(2, -1) }; route.Settings = settings; route.Receive(smtpMessage); }
public EmailService(SmtpSettings smtpSettings) { _smtpSettings = smtpSettings; }
public static void SendPublishRejectionNotification( SmtpSettings smtpSettings, SiteSettings siteSettings, SiteUser rejectingUser, SiteUser draftSubmissionUser, ContentWorkflow rejectedWorkflow, string rejectionReason ) { CultureInfo defaultCulture = SiteUtils.GetDefaultUICulture(); string messageTemplate = String.Empty; string messageSubject = String.Empty; List <string> messageRecipients = new List <string>(); if (Email.IsValidEmailAddressSyntax(rejectedWorkflow.RecentActionByUserEmail)) { messageRecipients.Add(rejectedWorkflow.RecentActionByUserEmail); } messageTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "PublishRequestRejectionNotification.config"); messageSubject = ResourceHelper.GetMessageTemplate(defaultCulture, "PublishRequestRejectionNotificationSubject.config").Replace("{SiteName}", siteSettings.SiteName); if (Email.IsValidEmailAddressSyntax(draftSubmissionUser.LoweredEmail)) { messageRecipients.Add(draftSubmissionUser.LoweredEmail); } StringBuilder message = new StringBuilder(); message.Append(messageTemplate); message.Replace("{ModuleTitle}", rejectedWorkflow.ModuleTitle); message.Replace("{PublishRequestedDate}", rejectedWorkflow.RecentActionOn.ToShortDateString()); message.Replace("{RejectionReason}", rejectionReason); message.Replace("{RejectedBy}", rejectingUser.Name); if (messageRecipients.Count < 1) { //no valid addresses -- log it log.Error("Failed to send workflow publish rejection message, no valid recipient email " + rejectedWorkflow.RecentActionByUserEmail + ", " + draftSubmissionUser.LoweredEmail + " message was " + message.ToString()); return; } foreach (string recipient in messageRecipients) { Email.Send( smtpSettings, siteSettings.DefaultEmailFromAddress, siteSettings.DefaultFromEmailAlias, rejectingUser.Email, recipient, string.Empty, string.Empty, messageSubject, message.ToString(), false, Email.PriorityNormal); } }
public SmtpMessageSender(Func<SmtpClient> smtpClientFactory, SmtpSettings smtpSettings) { _smtpClientFactory = smtpClientFactory; _smtpSettings = smtpSettings; }
public override void UserRegisteredHandler(object sender, UserRegisteredEventArgs e) { //if (sender == null) return; if (e == null) { return; } if (e.SiteUser == null) { return; } if (!WebConfigSettings.NotifyAdminsOnNewUserRegistration) { return; } log.Debug("NotifyAdminUserRegisteredHandler called for new user " + e.SiteUser.Email); if (HttpContext.Current == null) { return; } //lookup admin users and send notification email with link to manage user SiteSettings siteSettings = CacheHelper.GetCurrentSiteSettings(); CultureInfo defaultCulture = ResourceHelper.GetDefaultCulture(); //Role adminRole = Role.GetRoleByName(siteSettings.SiteId, "Admins"); //if (adminRole == null) //{ // // TODO: log it? // return; //} //DataTable admins = SiteUser.GetRoleMembers(adminRole.RoleId); string subjectTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "NotifyAdminofNewUserRegistationSubject.config"); string textBodyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "NotifyAdminofNewUserRegistationMessage.config"); string siteRoot = SiteUtils.GetNavigationSiteRoot(); SmtpSettings smtpSettings = SiteUtils.GetSmtpSettings(); List <string> adminEmails = SiteUser.GetEmailAddresses(siteSettings.SiteId, "Admins;"); //foreach (DataRow row in admins.Rows) foreach (string email in adminEmails) { if (WebConfigSettings.EmailAddressesToExcludeFromAdminNotifications.IndexOf(email, StringComparison.InvariantCultureIgnoreCase) > -1) { continue; } EmailMessageTask messageTask = new EmailMessageTask(smtpSettings); messageTask.EmailFrom = siteSettings.DefaultEmailFromAddress; //messageTask.EmailTo = row["Email"].ToString(); messageTask.EmailTo = email; messageTask.Subject = string.Format( defaultCulture, subjectTemplate, e.SiteUser.Email, siteRoot ); string manageUserLink = siteRoot + "/Admin/ManageUsers.aspx?userid=" + e.SiteUser.UserId.ToString(CultureInfo.InvariantCulture); messageTask.TextBody = string.Format( defaultCulture, textBodyTemplate, siteSettings.SiteName, siteRoot, manageUserLink ); messageTask.SiteGuid = siteSettings.SiteGuid; messageTask.QueueTask(); } WebTaskManager.StartOrResumeTasks(); }