Skip to content

Commit

Permalink
Refactor Email and other minor fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
enkodellc committed Jul 18, 2019
1 parent 322a486 commit 7db453c
Show file tree
Hide file tree
Showing 8 changed files with 60 additions and 53 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,9 @@ This project is licensed under the terms of the [MIT license](LICENSE).
## News
### 0.1.7 - In Progress
- User Profile Management
- Propagating Errors properly to Toasts
- Refactor Email Settings and API
- Error Handling Middleware to Propagating Errors properly to Toasts


### 0.1.6
- Email confirmation on Registration
Expand Down
11 changes: 3 additions & 8 deletions src/BlazorBoilerplate.Client/Pages/TestEmail.razor
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,14 @@
@inject IMatToaster matToaster

<h1>Send Email</h1>
<p>Test out SMTP email sending with MailKit. This will send out an email using a default template if you have setup your smtp server or other email configuration.</p>
<p>Test out SMTP email sending with MailKit. This will send out an email using a default "Test" template if you have setup your smtp server in <i>appsettings.json</i>.</p>
<EditForm Model="@emailParameters" OnValidSubmit="@SendEmail">
<DataAnnotationsValidator />
<ValidationSummary />
<fieldset>
<div class="form-group">
<MatTextField @bind-value="@emailParameters.ToAddress" Label="Email" Icon="mail_outline" IconTrailing="true" FullWidth="true" Required="true"></MatTextField>
</div>
@*<div class="form-group">
<MatTextField @bind-value="@emailParameters.Subject" Label="Subject" Icon="lock_outline" IconTrailing="true" FullWidth="true" Required="true"></MatTextField>
</div>
<div class="form-group">
<MatTextField @bind-value="@emailParameters.Body" Label="Message" Icon="lock_outline" IconTrailing="true" FullWidth="true" Required="true"></MatTextField>
</div>*@
<div class="form-group d-flex justify-content-end">
<MatButton Type="submit" Raised="true">Send Test Template Email</MatButton>
</div>
Expand All @@ -30,14 +24,15 @@
EmailParameters emailParameters { get; set; } = new EmailParameters();
protected override async Task OnInitAsync()
{
//set the template name so it passes model validation
emailParameters.TemplateName = "Test";
}

async Task SendEmail()
{
try
{
var result = await Http.PostJsonAsync<EmailParameters>("api/Email/Email", emailParameters);
await Http.PostJsonAsync<EmailParameters>("api/Email/Send", emailParameters);
matToaster.Add("Email has been Sent", MatToastType.Success);
}
catch (Exception ex)
Expand Down
17 changes: 9 additions & 8 deletions src/BlazorBoilerplate.Server/Controllers/AuthorizeController.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Security.Claims;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using BlazorBoilerplate.Shared;
using BlazorBoilerplate.Server.Helpers;
using BlazorBoilerplate.Server.Services;
using BlazorBoilerplate.Shared;
using System.Security.Claims;
using BlazorBoilerplate.Server.Models;

namespace BlazorBoilerplate.Server.Models
namespace BlazorBoilerplate.Server.Controllers
{
[Route("api/Authorize")]
[Route("api/[controller]")]
[ApiController]
public class AuthorizeController : ControllerBase
{
Expand Down Expand Up @@ -45,15 +46,15 @@ public AuthorizeController(UserManager<ApplicationUser> userManager,
public UserInfo GetUser()
{
return User.Identity.IsAuthenticated
? new UserInfo {UserName = User.Identity.Name, IsAuthenticated = true}
? new UserInfo { UserName = User.Identity.Name, IsAuthenticated = true }
: LoggedOutUser;
}

//[HttpGet("")]
//[Authorize]
//public List<UserInfo> GetUsers()
//{

//}

[HttpPost("Login")]
Expand Down Expand Up @@ -147,7 +148,7 @@ public async Task<IActionResult> Register(RegisterParameters parameters)
string callbackUrl = string.Format("{0}/Account/ConfirmEmail/{1}?token={2}", _configuration["ApplicationUrl"], user.Id, token);

var email = new EmailMessage();
email.ToAddresses.Add(new EmailAddress(user.Email, user.Email));
email.ToAddresses.Add(new EmailAddress(user.Email, user.Email));
email = EmailTemplates.BuildNewUserConfirmationEmail(email, user.UserName, user.Email, callbackUrl, user.Id.ToString(), token); //Replace First UserName with Name if you want to add name to Registration Form

_logger.LogInformation("New user registered: {0}", user);
Expand Down Expand Up @@ -339,7 +340,7 @@ private async Task<UserInfo> BuildUserInfo()
UserName = User.Identity.Name,
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
LastName = user.LastName,
ExposedClaims = User.Claims
//Optionally: filter the claims you want to expose to the client
//.Where(c => c.Type == "test-claim")
Expand Down
63 changes: 35 additions & 28 deletions src/BlazorBoilerplate.Server/Controllers/EmailController.cs
Original file line number Diff line number Diff line change
@@ -1,59 +1,66 @@
using BlazorBoilerplate.Shared;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BlazorBoilerplate.Server.Models;
using Microsoft.Extensions.Logging;
using BlazorBoilerplate.Shared;
using BlazorBoilerplate.Server.Models;
using BlazorBoilerplate.Server.Services;
using BlazorBoilerplate.Server.Helpers;

namespace BlazorBoilerplate.Server.Controllers
{
[Route("api/[controller]/[action]")]
[Route("api/[controller]")]
[Authorize]
public class EmailController : Controller
[ApiController]
public class EmailController : ControllerBase
{
// Logger instance
ILogger<SampleDataController> _logger;
ILogger<EmailController> _logger;
IEmailService _emailService;

public EmailController(IEmailService emailService, ILogger<SampleDataController> logger)
public EmailController(IEmailService emailService, ILogger<EmailController> logger)
{
_logger = logger;
_emailService = emailService;
}

[HttpPost]
[Authorize]
[ProducesResponseType(200, Type = typeof(string))]
public async Task<IActionResult> Email(EmailParameters parameters)
[HttpPost("Send")]
[ProducesResponseType(204)]
[ProducesResponseType(400)]
public async Task<IActionResult> Send(EmailParameters parameters)
{
parameters.Subject = "test";
parameters.Body = "my email";
if (!ModelState.IsValid)
return BadRequest(ModelState.Values.SelectMany(state => state.Errors)
.Select(error => error.ErrorMessage)
.FirstOrDefault());

var email = new EmailMessage();

email.ToAddresses.Add(new EmailAddress(parameters.ToName, parameters.ToAddress));
//email.Subject = parameters.Subject; //for demo force a Template to reduce spam
//email.Body = parameters.Body;

if (string.IsNullOrEmpty(parameters.TemplateName))
//This forces all emails from the API to use the Test template to prevent spam
parameters.TemplateName = "Test";

//Send a Template email or a custom one since it is hardcoded to Test template it will not do a custom email.
if (!string.IsNullOrEmpty(parameters.TemplateName))
{
parameters.TemplateName = "Test";
switch (parameters.TemplateName)
{
case "Test":
email = EmailTemplates.BuildTestEmail(email); //example of email Template usage
break;
default:
break;
}
}

switch (parameters.TemplateName)
else
{
case "Test":
email = EmailTemplates.BuildTestEmail(email,parameters.ToName); //example of email Template usage
break;
default:
break;
email.Subject = parameters.Subject;
email.Body = parameters.Body;
}

//Add a new From Address if you so choose
//Add a new From Address if you so choose, default is set in appsettings.json
//email.FromAddresses.Add(new EmailAddress("New From Name", "[email protected]"));
_logger.LogInformation("Test Email: {0}", email.Subject);

Expand Down
6 changes: 3 additions & 3 deletions src/BlazorBoilerplate.Server/Helpers/EmailTemplates.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,16 @@ public static void Initialize(IWebHostEnvironment webHostEnvironment)
_webHostEnvironment = webHostEnvironment;
}

public static EmailMessage BuildTestEmail(EmailMessage emailMessage, string recepientName)
public static EmailMessage BuildTestEmail(EmailMessage emailMessage)
{
if (testEmailTemplate == null)
testEmailTemplate = ReadPhysicalFile("Helpers/Templates/TestEmail.template");

emailMessage.Body = testEmailTemplate
.Replace("{user}", recepientName)
.Replace("{user}", emailMessage.ToAddresses[0].Name)
.Replace("{testDate}", DateTime.Now.ToString());

emailMessage.Subject = string.Format("Hello {0} from Blazor Boilerplate", recepientName);
emailMessage.Subject = string.Format("Hello {0} from Blazor Boilerplate", emailMessage.ToAddresses[0].Name);

return emailMessage;
}
Expand Down
7 changes: 4 additions & 3 deletions src/BlazorBoilerplate.Server/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@

"EmailConfiguration": {
"FromName": "Blazor Boilerplate",
"FromEmailAddress": "[email protected]",
"FromAddress": "[email protected]",
"ReplyToAddress": "[email protected]",
"SmtpServer": "smtp.gmail.com",
"SmtpPort": 465,
"SmtpUseSSL": true,
"SmtpUserName": "[email protected]",
"SmtpPassword": "xxx"
"SmtpUsername": "[email protected]",
"SmtpPassword": "PASSWORD"
},


"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
Expand Down
4 changes: 2 additions & 2 deletions src/BlazorBoilerplate.Server/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@

"EmailConfiguration": {
"FromName": "Blazor Boilerplate",
"FromEmailAddress": "[email protected]",
"FromAddress": "[email protected]",
"ReplyToAddress": "[email protected]",
"SmtpServer": "smtp.gmail.com",
"SmtpPort": 465,
"SmtpUseSSL": true,
"SmtpUserName": "[email protected]",
"SmtpPassword": "xxx"
"SmtpPassword": "PASSWORD"
},

"Serilog": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="System.ComponentModel.Annotations" Version="4.6.0-preview6.19303.8" />
</ItemGroup>

Expand Down

0 comments on commit 7db453c

Please sign in to comment.