public void SendEmailReport(DateTime reportDate, SiteConfig siteConfig, IBlogDataService dataService, ILoggingDataService loggingService) { MailMessage emailMessage = new MailMessage(); if (siteConfig.NotificationEMailAddress != null && siteConfig.NotificationEMailAddress.Length > 0) { emailMessage.To.Add(siteConfig.NotificationEMailAddress); } else { emailMessage.To.Add(siteConfig.Contact); } emailMessage.Subject = String.Format("Weblog Daily Activity Report for '{0}'", reportDate.ToLongDateString()); emailMessage.Body = GenerateReportEmailBody(reportDate); emailMessage.IsBodyHtml = true; emailMessage.BodyEncoding = System.Text.Encoding.UTF8; emailMessage.From = new MailAddress(siteConfig.Contact); SendMailInfo sendMailInfo = new SendMailInfo(emailMessage, siteConfig.SmtpServer, siteConfig.EnableSmtpAuthentication, siteConfig.UseSSLForSMTP, siteConfig.SmtpUserName, siteConfig.SmtpPassword, siteConfig.SmtpPort); dataService.AddTracking(null, sendMailInfo); // use this with null tracking object, just to get the email sent loggingService.AddEvent(new EventDataItem(EventCodes.ReportMailerReportSent, "", "")); }
public async Task <bool> SendMailAsync(string subject, string body, string[] toRecipients, string[] ccRecipients = null, Attachement[] attachements = null) { var connectionInfo = BuildConnectionInfo(); var sendMailInfo = new SendMailInfo { Subject = subject, Body = $"<html>{body}</html>", ToRecipients = toRecipients, CCRecipients = ccRecipients }; if (attachements?.Any() ?? false) { sendMailInfo.Attachments = new AttachmentInfo[attachements.Count()]; for (int i = 0; i < attachements.Count(); i++) { sendMailInfo.Attachments[i] = new AttachmentInfo { Name = attachements[i].Filename, Bytes = attachements[i].Contents } } ; } try { await SendMailAsync(connectionInfo, sendMailInfo); return(true); } catch (Exception) { return(false); } }
private Task SendMailAsync(ConnectionInfo connectionInfo, SendMailInfo sendMailInfo) { var binding = MailServiceClient.EndpointConfiguration.CustomBinding_IMailService; var endpoint = GetEndpointAddress(); var mailService = new MailServiceClient(binding, endpoint); mailService.ChannelFactory.Endpoint.EndpointBehaviors.Add(new ClientViaBehavior(new Uri(_options.ClientViaUrl))); return(mailService.SendMailAsync(connectionInfo, sendMailInfo)); }
private SendMailInfo ComposeMail() { MailMessage emailMessage = new MailMessage(); if (requestPage.SiteConfig.NotificationEMailAddress != null && requestPage.SiteConfig.NotificationEMailAddress.Length > 0) { emailMessage.To.Add(requestPage.SiteConfig.NotificationEMailAddress); } else { emailMessage.To.Add(requestPage.SiteConfig.Contact); } string from = HttpUtility.HtmlEncode(email.Text); emailMessage.Subject = String.Format ("Weblog Mail from '{0} ({1})' on '{2}'" , HttpUtility.HtmlEncode(name.Text) , from , HttpUtility.HtmlEncode(requestPage.SiteConfig.Title)); emailMessage.Body = HttpUtility.HtmlEncode(comment.Text); emailMessage.IsBodyHtml = false; emailMessage.BodyEncoding = System.Text.Encoding.UTF8; if (from != null && from.Length > 0) { emailMessage.From = new MailAddress(from); } else { emailMessage.From = new MailAddress(requestPage.SiteConfig.Contact); } emailMessage.Headers.Add("Sender", requestPage.SiteConfig.Contact); // add the X-Originating-IP header string hostname = Dns.GetHostName(); IPHostEntry ipHostEntry = Dns.GetHostEntry(hostname); if (ipHostEntry.AddressList.Length > 0) { emailMessage.Headers.Add("X-Originating-IP", ipHostEntry.AddressList[0].ToString()); } SendMailInfo sendMailInfo = new SendMailInfo(emailMessage, requestPage.SiteConfig.SmtpServer, requestPage.SiteConfig.EnableSmtpAuthentication, requestPage.SiteConfig.UseSSLForSMTP, requestPage.SiteConfig.SmtpUserName, requestPage.SiteConfig.SmtpPassword, requestPage.SiteConfig.SmtpPort); return(sendMailInfo); }
/// <summary> /// 发送注册邮件 /// </summary> /// <param name="account"></param> /// <returns></returns> public Result SendRegistEmail(Account account) { Result result = new Result() { Status = true, Message = "发送邮件成功", StatusCode = "SR000" }; try { //生成code码加入缓存 设置时效日期 if (account != null) { byte[] phonebyte = Encoding.UTF8.GetBytes(account.Phone.ToString()); string code = Base64Engine.ToBase64String(phonebyte); CookieUtils.SetCookie(string.Format("code{0}", account.Phone), code, DateTime.Now.AddHours(1)); SendMailInfo sendinfo = new SendMailInfo(); using (StreamReader sr = File.OpenText(AppDomain.CurrentDomain.BaseDirectory + "VerificationMail.html")) { sendinfo.Content = sr.ReadToEnd(); } sendinfo.Title = "验证账户"; if (!string.IsNullOrEmpty(sendinfo.Content)) { sendinfo.Content = sendinfo.Content.Replace("(手机)", account.Phone.ToString()); sendinfo.Content = sendinfo.Content.Replace("(邮箱)", account.Email); sendinfo.Content = sendinfo.Content.Replace("(验证码)", code); } VerifiedMail.Sender.AddSend(sendinfo, new List <string>() { account.Email }); } } catch (Exception ex) { result.Status = false; result.Message = string.Format("邮件验证出错 /r/n{0}", ex.Message); result.StatusCode = "EX000"; LoggerUtils.LogIn(LoggerUtils.ColectExceptionMessage(ex, "At service:SendRegistEmail() .AccountService"), LogType.ErrorLog); } return(result); }
protected void buttonTestSMTP_Click(object sender, EventArgs e) { SharedBasePage requestPage = Page as SharedBasePage; SiteConfig siteConfig = requestPage.SiteConfig; if (textSmtpServer.Text != "" & textNotificationEmailAddress.Text != "") { MailMessage emailMessage = new MailMessage(); emailMessage.To.Add(textNotificationEmailAddress.Text); emailMessage.Subject = String.Format("dasBlog test message"); emailMessage.Body = String.Format("This is a test message from dasBlog. If you are reading this then everything is working properly."); emailMessage.IsBodyHtml = false; emailMessage.BodyEncoding = Encoding.UTF8; emailMessage.From = new MailAddress(siteConfig.Contact); SendMailInfo sendMailInfo = new SendMailInfo(emailMessage, textSmtpServer.Text, checkEnableSmtpAuthentication.Checked, checkUseSSLForSMTP.Checked, textSmtpUsername.Text, textSmtpPassword.Text, int.Parse(textSmtpPort.Text)); try { sendMailInfo.SendMyMessage(); } catch (Exception ex) { //RyanG: Decode the real reason the error occured by looking at the inner exceptions StringBuilder exceptionMessage = new StringBuilder(); Exception lastException = ex; while (lastException != null) { if (exceptionMessage.Length > 0) { exceptionMessage.Append("; "); } exceptionMessage.Append(lastException.Message); lastException = lastException.InnerException; } ILoggingDataService logService = requestPage.LoggingService; logService.AddEvent( new EventDataItem(EventCodes.SmtpError, "", exceptionMessage.ToString())); Response.Redirect("FormatPage.aspx?path=SiteConfig/pageerror.format.html", true); } } }
/// <summary> /// 发送忘记密码验证码 /// </summary> /// <param name="mail"></param> /// <returns></returns> public Result SendForgetVerificationCode(string mail) { Result result = new Result() { Status = true, Message = "发送邮件成功", StatusCode = "SR000" }; try { //生成code码加入缓存 设置时效日期 if (!string.IsNullOrEmpty(mail)) { string code = VerificationUtils.GetVefication(); CookieUtils.SetCookie(string.Format("forget{0}", mail), code, DateTime.Now.AddMinutes(30)); SendMailInfo sendinfo = new SendMailInfo(); using (StreamReader sr = File.OpenText(AppDomain.CurrentDomain.BaseDirectory + "ForgetVerificationMail.html")) { sendinfo.Content = sr.ReadToEnd(); } sendinfo.Title = string.Format("你此次重置密码的验证码是:{0}", code); if (!string.IsNullOrEmpty(sendinfo.Content)) { sendinfo.Content = sendinfo.Content.Replace("(手机)", mail); sendinfo.Content = sendinfo.Content.Replace("(验证码)", code); } VerifiedMail.Sender.AddSend(sendinfo, new List <string>() { "*****@*****.**" }); } } catch (Exception ex) { result.Status = false; result.Message = string.Format("忘记密码邮件验证出错 /r/n{0}", ex.Message); result.StatusCode = "EX000"; LoggerUtils.LogIn(LoggerUtils.ColectExceptionMessage(ex, "At service:SendForgetVerificationCode() .AccountService"), LogType.ErrorLog); } return(result); }
protected void mailSend_Click(object sender, System.EventArgs e) { if (CaptchaControl1.Enabled && requestPage.SiteConfig.EnableCaptcha == true) { if (CaptchaControl1.UserValidated == false) { return; } } if (Page.IsValid) { if (rememberMe.Checked) { string path = HttpRuntime.AppDomainAppVirtualPath; //We don't encode the name so High Latin folks like Ren Drie?el don't break // the Http Input Validation stuff. HttpCookie cookieName = new HttpCookie("name", name.Text); cookieName.Path = path; Response.Cookies.Add(cookieName); HttpCookie cookieEmail = new HttpCookie("email", HttpUtility.HtmlEncode(email.Text)); cookieEmail.Path = path; Response.Cookies.Add(cookieEmail); Response.Cookies["name"].Expires = DateTime.MaxValue; Response.Cookies["email"].Expires = DateTime.MaxValue; } if (requestPage.SiteConfig.SendCommentsByEmail && !String.IsNullOrEmpty(requestPage.SiteConfig.SmtpServer)) { SendMailInfo defaultMailInfo = ComposeMail(); requestPage.DataService.RunActions(new object[] { defaultMailInfo }); string commentShort = defaultMailInfo.Message.Body.Replace("\n", " "); if (commentShort.Length > 50) { commentShort = commentShort.Substring(0, 50) + "..."; } requestPage.LoggingService.AddEvent(new EventDataItem(EventCodes.CommentEmail, commentShort, string.Format("{0} {1}", defaultMailInfo.Message.From, HttpUtility.HtmlEncode(name.Text)))); } Response.Redirect(SiteUtilities.GetStartPageUrl(requestPage.SiteConfig), false); } }
private object[] ComposeMailForUsers(Entry entry, Comment c) { List <object> actions = new List <object>(); foreach (User user in SiteSecurity.GetSecurity().Users) { if (user.EmailAddress == null || user.EmailAddress.Length == 0) { continue; } if (user.NotifyOnAllComment || (user.NotifyOnOwnComment && entry.Author.ToUpper() == user.Name.ToUpper())) { SendMailInfo sendMailInfo = ComposeMail(c); sendMailInfo.Message.To.Add(user.EmailAddress); actions.Add(sendMailInfo); } } return(actions.ToArray()); }
private SendMailInfo ComposeMail(Comment c) { SharedBasePage requestPage = Page as SharedBasePage; MailMessage emailMessage = new MailMessage(); if (requestPage.SiteConfig.NotificationEMailAddress != null && requestPage.SiteConfig.NotificationEMailAddress.Length > 0) { emailMessage.To.Add(requestPage.SiteConfig.NotificationEMailAddress); } else { emailMessage.To.Add(requestPage.SiteConfig.Contact); } emailMessage.Sender = new MailAddress(requestPage.SiteConfig.Contact); emailMessage.Subject = String.Format("Weblog comment by '{0}' from '{1}' on '{2}'", c.Author, c.AuthorHomepage, c.TargetTitle); if (requestPage.SiteConfig.CommentsRequireApproval) { emailMessage.Body = String.Format("{0}\r\nComments page: {1}\r\n\r\nApprove comment: {2}\r\n\r\nDelete Comment: {3}", HttpUtility.HtmlDecode(c.Content), SiteUtilities.GetCommentViewUrl(c.TargetEntryId), SiteUtilities.GetCommentApproveUrl(c.TargetEntryId, c.EntryId), SiteUtilities.GetCommentDeleteUrl(c.TargetEntryId, c.EntryId)); } else { emailMessage.Body = String.Format("{0}\r\nComments page: {1}\r\n\r\nDelete Comment: {2}", HttpUtility.HtmlDecode(c.Content), SiteUtilities.GetCommentViewUrl(c.TargetEntryId), SiteUtilities.GetCommentDeleteUrl(c.TargetEntryId, c.EntryId)); if (c.SpamState == SpamState.Spam) { emailMessage.Body += "\r\nNot Spam: " + SiteUtilities.GetCommentApproveUrl(c.TargetEntryId, c.EntryId); } } if (requestPage.SiteConfig.EnableSpamBlockingService && (c.SpamState != SpamState.Spam)) { emailMessage.Body += "\r\n\r\nReport as SPAM: " + SiteUtilities.GetCommentReportUrl(requestPage.SiteConfig, c.TargetEntryId, c.EntryId) + "\r\n (Reporting SPAM will also delete the comment.)"; } emailMessage.Body += "\r\n\r\n" + ApplicationResourceTable.GetSpamStateDescription(c.SpamState); emailMessage.IsBodyHtml = false; emailMessage.BodyEncoding = System.Text.Encoding.UTF8; if (c.AuthorEmail != null && c.AuthorEmail.Length > 0) { emailMessage.From = new MailAddress(c.AuthorEmail); } else { emailMessage.From = new MailAddress(requestPage.SiteConfig.Contact); } emailMessage.Headers.Add("Sender", requestPage.SiteConfig.Contact); // add the X-Originating-IP header string hostname = Dns.GetHostName(); IPHostEntry ipHostEntry = Dns.GetHostEntry(hostname); if (ipHostEntry.AddressList.Length > 0) { emailMessage.Headers.Add("X-Originating-IP", ipHostEntry.AddressList[0].ToString()); } SendMailInfo sendMailInfo = new SendMailInfo(emailMessage, requestPage.SiteConfig.SmtpServer, requestPage.SiteConfig.EnableSmtpAuthentication, requestPage.SiteConfig.UseSSLForSMTP, requestPage.SiteConfig.SmtpUserName, requestPage.SiteConfig.SmtpPassword, requestPage.SiteConfig.SmtpPort); return(sendMailInfo); }
public void AddNewComment(string name, string email, string homepage, string comment, string entryId, bool openid) { SharedBasePage requestPage = Page as SharedBasePage; // if we allow tags, use the allowed tags, otherwise use an empty array ValidTagCollection allowedTags = (requestPage.SiteConfig.CommentsAllowHtml ? requestPage.SiteConfig.AllowedTags : new ValidTagCollection(null)); Entry entry = requestPage.DataService.GetEntry(entryId); if ((entry != null) && SiteUtilities.AreCommentsAllowed(entry, requestPage.SiteConfig)) { Comment c = new Comment(); c.Initialize(); c.OpenId = openid; c.Author = HttpUtility.HtmlEncode(name); c.AuthorEmail = HttpUtility.HtmlEncode(email); c.AuthorHomepage = FixUrl(homepage); c.AuthorIPAddress = Request.UserHostAddress; c.AuthorUserAgent = Request.UserAgent; c.Referer = Request.UrlReferrer != null?Request.UrlReferrer.ToString() : String.Empty; // clean the code from html tags c.TargetEntryId = entryId; c.TargetTitle = entry.Title; if (requestPage.SiteConfig.CommentsRequireApproval == true && (requestPage.SiteConfig.SmtpServer == null || requestPage.SiteConfig.SmtpServer.Length == 0)) { requestPage.LoggingService.AddEvent(new EventDataItem(EventCodes.Error, "ERROR: Comment Moderation is turned on, but you haven't configured an SMTP Server for sending mail!", "")); } // if comments require moderation, they are not public. // except when the commenter is a contributor if (SiteSecurity.IsValidContributor()) { c.IsPublic = true; } else { // bypass spam when the comment is authenticated by openid en openid doesn't require approval if (requestPage.SiteConfig.EnableSpamBlockingService && (requestPage.SiteConfig.BypassSpamOpenIdComment && openid) == false) { // make sure to send the unfiltered comment for analysis by external service c.Content = comment; bool externalServiceSucceeded = false; try { if (requestPage.SiteConfig.SpamBlockingService.IsSpam(c)) { potentialSpamSubmitted = true; if (!requestPage.SiteConfig.EnableSpamModeration) { // abort saving the comment requestPage.LoggingService.AddEvent(new EventDataItem(EventCodes.CommentBlocked, String.Format("Blocking suspected spam from {0} {1} [{2}].", c.Author, c.AuthorEmail, c.AuthorIPAddress), SiteUtilities.GetPermaLinkUrl(entryId))); clearCommentInput(); return; } c.SpamState = SpamState.Spam; c.IsPublic = false; } else { c.SpamState = SpamState.NotSpam; c.IsPublic = true; } externalServiceSucceeded = true; } catch (Exception ex) { requestPage.LoggingService.AddEvent(new EventDataItem(EventCodes.Error, String.Format("The external spam blocking service failed for comment {0}. Original exception: {1}", c.EntryId, ex), SiteUtilities.GetPermaLinkUrl(entryId))); } if (!externalServiceSucceeded) { // If the external service fails, we will hide the comment, but not delete it, // even if moderation is disabled. c.SpamState = SpamState.NotChecked; if (doesFeedbackHaveSpamPotential(c)) { potentialSpamSubmitted = true; c.IsPublic = false; } else { c.IsPublic = true; } } } else { c.IsPublic = true; } // If comment moderation enabled, hide all comments regardless of the what the external spam service says if (requestPage.SiteConfig.CommentsRequireApproval) { c.IsPublic = false; } } // FilterHtml html encodes anything we don't like string filteredText = SiteUtilities.FilterHtml(comment, allowedTags); c.Content = filteredText; if (requestPage.SiteConfig.SendCommentsByEmail && requestPage.SiteConfig.SmtpServer != null && requestPage.SiteConfig.SmtpServer.Length > 0) { SendMailInfo defaultMailInfo = ComposeMail(c); requestPage.DataService.AddComment(c, defaultMailInfo); requestPage.DataService.RunActions(ComposeMailForUsers(entry, c)); string commentShort = c.Content.Replace("\n", ""); if (commentShort.Length > 50) { commentShort = commentShort.Substring(0, 50) + "..."; } requestPage.LoggingService.AddEvent( new EventDataItem( EventCodes.CommentAdded, commentShort, SiteUtilities.GetCommentViewUrl(entryId))); } else { requestPage.DataService.AddComment(c); } clearCommentInput(); // break the caching requestPage.DataCache.Remove("BlogCoreData"); Session.Remove("pendingComment"); Session.Remove("pendingEntryId"); //Send the user to the comment they JUST posted. if (!potentialSpamSubmitted) { Response.Redirect(SiteUtilities.GetCommentViewUrl(c.TargetEntryId) + "#" + c.EntryId); } } }
public string ping( string sourceUri, string targetUri) { if (!siteConfig.EnablePingbackService) { throw new ServiceDisabledException(); } string returnValue = "0"; if (ReferralBlackList.IsBlockedReferrer(sourceUri)) { if (siteConfig.EnableReferralUrlBlackList404s) { this.Context.Response.StatusCode = 404; this.Context.Response.End(); throw new XmlRpcFaultException(404, "not found"); } } try { string entryId = null; // OmarS: need to rewrite the URL so w can find the entryId Uri uriTargetUri = new Uri(SiteUtilities.MapUrl(targetUri)); string query = uriTargetUri.Query; if (query.Length > 0 && query[0] == '?') { query = query.Substring(1); } else { return(returnValue); } string[] queryItems = query.Split('&'); if (queryItems == null) { return(returnValue); } foreach (string queryItem in queryItems) { string[] keyvalue = queryItem.Split('='); if (keyvalue.Length == 2) { string key = keyvalue[0]; string @value = keyvalue[1]; if (key == "guid") { entryId = @value; break; } } } if (entryId != null) { Entry entry = dataService.GetEntry(entryId); if (entry != null) { Tracking t = new Tracking(); t.PermaLink = sourceUri; t.Referer = this.Context.Request.UrlReferrer != null?this.Context.Request.UrlReferrer.ToString() : String.Empty; t.RefererBlogName = sourceUri; t.RefererExcerpt = String.Empty; t.RefererTitle = sourceUri; t.TargetEntryId = entryId; t.TargetTitle = entry.Title; t.TrackingType = TrackingType.Pingback; t.RefererIPAddress = this.Context.Request.UserHostAddress; ISpamBlockingService spamBlockingService = siteConfig.SpamBlockingService; if (spamBlockingService != null) { bool isSpam = false; try { isSpam = spamBlockingService.IsSpam(t); } catch (Exception ex) { logDataService.AddEvent(new EventDataItem(EventCodes.Error, String.Format("The external spam blocking service failed for pingback from {0}. Original exception: {1}", sourceUri, ex), targetUri)); } if (isSpam) { //TODO: May provide moderation in the future. For now we just ignore the pingback logDataService.AddEvent(new EventDataItem( EventCodes.PingbackBlocked, "Pingback blocked from " + sourceUri + " because it was considered spam by the external blocking service.", targetUri, sourceUri)); System.Web.HttpContext.Current.Response.StatusCode = 404; System.Web.HttpContext.Current.Response.End(); throw new XmlRpcFaultException(404, "not found"); } } if (siteConfig.SendPingbacksByEmail && siteConfig.SmtpServer != null && siteConfig.SmtpServer.Length > 0) { MailMessage emailMessage = new MailMessage(); if (siteConfig.NotificationEMailAddress != null && siteConfig.NotificationEMailAddress.Length > 0) { emailMessage.To.Add(siteConfig.NotificationEMailAddress); } else { emailMessage.To.Add(siteConfig.Contact); } emailMessage.Subject = String.Format("Weblog pingback by '{0}' on '{1}'", sourceUri, t.TargetTitle); emailMessage.Body = String.Format("You were pinged back by\n{0}\r\non your weblog entry '{1}'\n({2}\r\n\r\nDelete Trackback: {3})", sourceUri, t.TargetTitle, SiteUtilities.GetPermaLinkUrl(entry), SiteUtilities.GetTrackbackDeleteUrl(entryId, t.PermaLink, t.TrackingType)); emailMessage.IsBodyHtml = false; emailMessage.BodyEncoding = System.Text.Encoding.UTF8; emailMessage.From = new MailAddress(siteConfig.Contact); SendMailInfo sendMailInfo = new SendMailInfo(emailMessage, siteConfig.SmtpServer, siteConfig.EnableSmtpAuthentication, siteConfig.UseSSLForSMTP, siteConfig.SmtpUserName, siteConfig.SmtpPassword, siteConfig.SmtpPort); dataService.AddTracking(t, sendMailInfo); } else { dataService.AddTracking(t); } logDataService.AddEvent( new EventDataItem(EventCodes.PingbackReceived, entry.Title, targetUri, sourceUri)); returnValue = sourceUri; } } } catch (Exception e) { ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e); return("0"); } return(returnValue); }
public void ProcessRequest(HttpContext context) { SiteConfig siteConfig = SiteConfig.GetSiteConfig(); string entryId; string title; string excerpt; string url; string blog_name; if (!siteConfig.EnableTrackbackService) { context.Response.StatusCode = 503; context.Response.Status = "503 Service Unavailable"; context.Response.End(); return; } // Try blocking them once, on the off chance they sent us a referrer string referrer = context.Request.UrlReferrer != null?context.Request.UrlReferrer.AbsoluteUri:""; if (ReferralBlackList.IsBlockedReferrer(referrer)) { if (siteConfig.EnableReferralUrlBlackList404s) { context.Response.StatusCode = 404; context.Response.End(); return; } } entryId = context.Request.QueryString["guid"]; if (context.Request.HttpMethod == "POST") { title = context.Request.Form["title"]; excerpt = context.Request.Form["excerpt"]; url = context.Request.Form["url"]; blog_name = context.Request.Form["blog_name"]; } /* GET is no longer in the Trackback spec. Keeping * this arround for testing. Just uncomment. * else if ( context.Request.HttpMethod == "GET" ) * { * title = context.Request.QueryString["title"]; * excerpt= context.Request.QueryString["excerpt"]; * url = context.Request.QueryString["url"]; * blog_name = context.Request.QueryString["blog_name"]; * } */ else { context.Response.Redirect(SiteUtilities.GetStartPageUrl(siteConfig)); return; } if (url != null && url.Length > 0) { try { // First line of defense, try blocking again with the URL they are tracking us back with if (ReferralBlackList.IsBlockedReferrer(url)) { if (siteConfig.EnableReferralUrlBlackList404s) { context.Response.StatusCode = 404; context.Response.End(); return; } } ILoggingDataService logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext()); IBlogDataService dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService); Entry entry = dataService.GetEntry(entryId); if (entry != null) { try { string requestBody = null; // see if this is a spammer HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; webRequest.Method = "GET"; webRequest.UserAgent = SiteUtilities.GetUserAgent(); HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse; // now we want to get the page contents of the target body using (StreamReader requestReader = new StreamReader(response.GetResponseStream())) { requestBody = requestReader.ReadToEnd(); } response.Close(); // the source URL in the page could be URL encoded like the ClickThroughHandler does string urlEncodedBaseUrl = HttpUtility.UrlEncode(SiteUtilities.GetBaseUrl()); // check to see if the source's page contains a link to us if (Regex.Match(requestBody, SiteUtilities.GetBaseUrl()).Success == false && Regex.Match(requestBody, urlEncodedBaseUrl).Success == false) { logService.AddEvent(new EventDataItem( EventCodes.TrackbackBlocked, context.Request.UserHostAddress + " because it did not contain a link", SiteUtilities.GetPermaLinkUrl(entryId), url, entry.Title )); context.Response.StatusCode = 404; context.Response.End(); return; } } catch { // trackback url is not even alive logService.AddEvent(new EventDataItem( EventCodes.TrackbackBlocked, context.Request.UserHostAddress + " because the server did not return a valid response", SiteUtilities.GetPermaLinkUrl(entryId), url, entry.Title )); context.Response.StatusCode = 404; context.Response.End(); return; } // if we've gotten this far, the trackback is real and valid Tracking t = new Tracking(); t.PermaLink = url; t.Referer = context.Request.UrlReferrer != null?context.Request.UrlReferrer.ToString() : String.Empty; t.RefererBlogName = blog_name; t.RefererExcerpt = excerpt; t.RefererTitle = title; t.RefererIPAddress = context.Request.UserHostAddress; t.TargetEntryId = entryId; t.TargetTitle = entry.Title; t.TrackingType = TrackingType.Trackback; ISpamBlockingService spamBlockingService = siteConfig.SpamBlockingService; if (spamBlockingService != null) { bool isSpam = false; try { isSpam = spamBlockingService.IsSpam(t); } catch (Exception ex) { logService.AddEvent(new EventDataItem(EventCodes.Error, String.Format("The external spam blocking service failed for trackback from {0}. Original exception: {1}", t.PermaLink, ex), SiteUtilities.GetPermaLinkUrl(entryId))); } if (isSpam) { //TODO: maybe we can add a configuration option to moderate trackbacks. // For now, we'll just avoid saving suspected spam logService.AddEvent(new EventDataItem( EventCodes.TrackbackBlocked, context.Request.UserHostAddress + " because it was considered spam by the external blocking service.", SiteUtilities.GetPermaLinkUrl(entryId), url, entry.Title )); context.Response.StatusCode = 404; context.Response.End(); return; } } if (siteConfig.SendTrackbacksByEmail && siteConfig.SmtpServer != null && siteConfig.SmtpServer.Length > 0) { MailMessage emailMessage = new MailMessage(); if (siteConfig.NotificationEMailAddress != null && siteConfig.NotificationEMailAddress.Length > 0) { emailMessage.To.Add(siteConfig.NotificationEMailAddress); } else { emailMessage.To.Add(siteConfig.Contact); } emailMessage.Subject = String.Format("Weblog trackback by '{0}' on '{1}'", t.PermaLink, t.TargetTitle); emailMessage.Body = String.Format("You were tracked back from\n{0}\r\non your weblog entry '{1}'\n({2}\r\n\r\nDelete Trackback: {3})", t.PermaLink, t.TargetTitle, SiteUtilities.GetPermaLinkUrl(entryId), SiteUtilities.GetTrackbackDeleteUrl(entryId, t.PermaLink, t.TrackingType)); emailMessage.IsBodyHtml = false; emailMessage.BodyEncoding = System.Text.Encoding.UTF8; emailMessage.From = new MailAddress(siteConfig.Contact); SendMailInfo sendMailInfo = new SendMailInfo(emailMessage, siteConfig.SmtpServer, siteConfig.EnableSmtpAuthentication, siteConfig.UseSSLForSMTP, siteConfig.SmtpUserName, siteConfig.SmtpPassword, siteConfig.SmtpPort); dataService.AddTracking(t, sendMailInfo); } else { dataService.AddTracking(t); } logService.AddEvent( new EventDataItem( EventCodes.TrackbackReceived, entry.Title, SiteUtilities.GetPermaLinkUrl(entryId), url)); // return the correct Trackback response // http://www.movabletype.org/docs/mttrackback.html context.Response.Write("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><response><error>0</error></response>"); return; } } catch (System.Threading.ThreadAbortException ex) { // absorb ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, ex); return; } catch (Exception exc) { // absorb ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc); // return the correct Trackback response // http://www.movabletype.org/docs/mttrackback.html context.Response.Write("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><response><error>1</error><message>" + exc.ToString() + "</message></response>"); return; } } if (entryId != null && entryId.Length > 0) { context.Response.Redirect(SiteUtilities.GetPermaLinkUrl(siteConfig, entryId)); } else { context.Response.Redirect(SiteUtilities.GetStartPageUrl(siteConfig)); } }