Skip to content

Commit

Permalink
Updates to newsletter template
Browse files Browse the repository at this point in the history
  • Loading branch information
rxtur committed Jan 20, 2019
1 parent 16640b3 commit 46bedb8
Show file tree
Hide file tree
Showing 10 changed files with 140 additions and 25 deletions.
45 changes: 43 additions & 2 deletions docs/SendGrid.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,49 @@ Currently, SendGrid only used by Newsletter widget. When guest subscribes to the
every time new post gets published, Blogifier goes over list of subscribers and sends notification
about new publication to every subscriber.


### Why not SMTP?
Plain SMTP client routes calls to actual SMTP email server, like Gmail or HotMail.
Unfortunately, most SMTP providers and hosters block 3rd party email traffic.
Cloud providers have limitations, but much more reliable.
Cloud providers have limitations, but much more reliable.

### Newsletter Template

There is default HTML template for a Newsletter: `/wwwroot/templates/newsletter.html`.
Newsletter emails will use this template as HTML content.

```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Newsletter</title>
</head>
<body>
<h2>{3}</h2>
<div>Just published on {0}</div>
<div>{4}</div>
<div><a href="{10}/posts/{6}">Keep reading...</a></div>
</body>
</html>
```

### Template Arguments

You can customize Newsletter template and use any of the arguments below putting
numeric values in the curly brackets. For example use "{0}" in template to output blog title.


```
var htmlContent = string.Format(template,
blog.Title, // 0
blog.Logo, // 1
blog.Cover, // 2
post.Title, // 3
post.Description, // 4
post.Content, // 5
post.Slug, // 6
post.Published, // 7
post.Cover, // 8
post.Author, // 9
siteUrl); // 10
```
17 changes: 10 additions & 7 deletions src/App/Pages/Admin/Posts/Edit.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ public class EditModel : AdminPageModel

IDataService _db;
INotificationService _ns;
ISendGridService _sg;
IEmailService _es;

public EditModel(IDataService db, INotificationService ns, ISendGridService sg)
public EditModel(IDataService db, INotificationService ns, IEmailService es)
{
_db = db;
_ns = ns;
_sg = sg;
_es = es;
}

public async Task OnGetAsync(int id)
Expand Down Expand Up @@ -70,10 +70,12 @@ public async Task<IActionResult> OnPostAsync()
//This is to prevent users from modifiyng other users or admin posts. -- manuta 9-16-2018
if (IsAdmin || _db.Authors.Single(a => a.Id == PostItem.Author.Id).AppUserName == User.Identity.Name)
{
if (PostItem.Status == SaveStatus.Publishing)
var status = PostItem.Status;

if (status == SaveStatus.Publishing)
PostItem.Published = DateTime.UtcNow;

if (PostItem.Status == SaveStatus.Unpublishing)
if (status == SaveStatus.Unpublishing)
PostItem.Published = DateTime.MinValue;

// fix for linux default datetime
Expand All @@ -87,10 +89,11 @@ public async Task<IActionResult> OnPostAsync()
PostItem = item;
Message = Resources.Saved;

if(PostItem.Status == SaveStatus.Publishing)
if(status == SaveStatus.Publishing)
{
var siteUrl = $"{Request.Scheme}://{Request.Host}";
List<string> emails = _db.Newsletters.All().Select(n => n.Email).ToList();
await _sg.SendNewsletters(PostItem, emails);
await _es.SendNewsletters(PostItem, emails, siteUrl);
}

return Redirect($"~/admin/posts/edit?id={PostItem.Id}");
Expand Down
1 change: 1 addition & 0 deletions src/App/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"SendGridApiKey": "YOUR-SENDGRID-API-KEY",
"SendGridEmailFrom": "[email protected]",
"SendGridEmailFromName": "Blog admin",
"GithubRepoUrl": "https://api.github.com/repos/blogifierdotnet/Blogifier/releases/latest",
"DemoMode": false
}
}
13 changes: 13 additions & 0 deletions src/App/wwwroot/templates/newsletter.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Newsletter</title>
</head>
<body>
<h2>{3}</h2>
<div>Just published on {0}</div>
<div>{4}</div>
<div><a href="{10}/posts/{6}">Keep reading...</a></div>
</body>
</html>
6 changes: 4 additions & 2 deletions src/Core/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
{
public class Constants
{
public static string ConfigSectionKey = "Blogifier";
public static string ConfigRepoKey = "GithubRepoUrl";

public static string NewestVersion = "last-version";
public static string UpgradeDirectory = "_upgrade";
public static string RepoReleaseUrl = "https://api.github.com/repos/blogifierdotnet/Blogifier/releases/latest";


// blog settings in custom fields
public static string BlogTitle = "blog-title";
public static string BlogDescription = "blog-description";
Expand Down
2 changes: 1 addition & 1 deletion src/Core/Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<Version>2.2.0.2</Version>
<Version>2.2.0.3</Version>
</PropertyGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/Core/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public static IServiceCollection AddAppServices(this IServiceCollection services
services.AddTransient<IImportService, ImportService>();
services.AddTransient<INotificationService, NotificationService>();
services.AddTransient<IWebService, WebService>();
services.AddTransient<ISendGridService, SendGridService>();
services.AddTransient<IEmailService, SendGridService>();

services.AddTransient<UserManager<AppUser>>();

Expand Down
35 changes: 27 additions & 8 deletions src/Core/Services/SendGridService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,37 +8,56 @@

namespace Core.Services
{
public interface ISendGridService
public interface IEmailService
{
Task SendNewsletters(PostItem postItem, List<string> emails);
Task SendNewsletters(PostItem postItem, List<string> emails, string siteUrl);
Task SendEmail(string to, string subject, string content);
}

public class SendGridService : ISendGridService
public class SendGridService : IEmailService
{
private readonly IConfiguration _config;
private readonly ILogger _logger;
IStorageService _storage;
IDataService _db;
BlogItem _blog;

public SendGridService(IConfiguration config, ILogger<SendGridService> logger)
public SendGridService(IDataService db, IConfiguration config, ILogger<SendGridService> logger, IStorageService storage)
{
_db = db;
_config = config;
_logger = logger;
_storage = storage;
}

public async Task SendNewsletters(PostItem postItem, List<string> emails)
public async Task SendNewsletters(PostItem post, List<string> emails, string siteUrl)
{
var blog = await _db.CustomFields.GetBlogSettings();
foreach (var email in emails)
{
var subject = "Newsletter: " + postItem.Title;
var htmlContent = postItem.Description;
var subject = post.Title;
var content = _storage.GetHtmlTemplate("newsletter");

var htmlContent = string.Format(content,
blog.Title, // 0
blog.Logo, // 1
blog.Cover, // 2
post.Title, // 3
post.Description, // 4
post.Content, // 5
post.Slug, // 6
post.Published, // 7
post.Cover, // 8
post.Author, // 9
siteUrl); // 10

await SendEmail(email, subject, htmlContent);
}
}

public async Task SendEmail(string to, string subject, string content)
{
var section = _config.GetSection("Blogifier");
var section = _config.GetSection(Constants.ConfigSectionKey);

if(section != null)
{
Expand Down
23 changes: 23 additions & 0 deletions src/Core/Services/StorageService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ public interface IStorageService
IList<string> GetAssets(string path);
IList<string> GetThemes();

string GetHtmlTemplate(string template);

Task<IEnumerable<AssetItem>> Find(Func<AssetItem, bool> predicate, Pager pager, string path = "");

Task Reset();
Expand Down Expand Up @@ -118,6 +120,27 @@ public IList<string> GetThemes()
return items;
}

public string GetHtmlTemplate(string template)
{
string content = "<p>Not found</p>";
try
{
var path = AppSettings.WebRootPath ?? Path.Combine(GetAppRoot(), "wwwroot");
path = Path.Combine(path, "templates");
path = Path.Combine(path, $"{template}.html");

if (File.Exists(path))
{
content = File.ReadAllText(path);
}
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
}
return content;
}

public async Task<AssetItem> UploadFormFile(IFormFile file, string root, string path = "")
{
path = path.Replace("/", _separator);
Expand Down
21 changes: 17 additions & 4 deletions src/Core/Services/WebService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.IO;
using Microsoft.Extensions.Configuration;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Threading.Tasks;
Expand All @@ -14,11 +15,13 @@ public interface IWebService
public class WebService : IWebService
{
IDataService _db;
IConfiguration _config;
static HttpClient client = new HttpClient();

public WebService(IDataService db)
public WebService(IDataService db, IConfiguration config)
{
_db = db;
_config = config;

// required by Github
if (!client.DefaultRequestHeaders.Contains("User-Agent"))
Expand All @@ -30,7 +33,8 @@ public WebService(IDataService db)
public async Task<string> CheckForLatestRelease()
{
string result = "";
HttpResponseMessage response = await client.GetAsync(Constants.RepoReleaseUrl);

HttpResponseMessage response = await client.GetAsync(getGithubUrl());

if (response.IsSuccessStatusCode)
{
Expand Down Expand Up @@ -69,7 +73,7 @@ public async Task<string> DownloadLatestRelease()
var msg = "";
try
{
HttpResponseMessage response = await client.GetAsync(Constants.RepoReleaseUrl);
HttpResponseMessage response = await client.GetAsync(getGithubUrl());
if (response.IsSuccessStatusCode)
{
var repo = await response.Content.ReadAsAsync<Data.Github.Repository>();
Expand Down Expand Up @@ -102,5 +106,14 @@ public async Task<string> DownloadLatestRelease()

return await Task.FromResult(msg);
}

string getGithubUrl()
{
var section = _config.GetSection(Constants.ConfigSectionKey);

return (section != null && !string.IsNullOrEmpty(section.GetValue<string>(Constants.ConfigRepoKey))) ?
section.GetValue<string>(Constants.ConfigRepoKey) :
"https://api.github.com/repos/blogifierdotnet/Blogifier/releases/latest";
}
}
}

0 comments on commit 46bedb8

Please sign in to comment.