Simple Send Function

This commit is contained in:
Alex Hyett 2018-12-12 10:56:09 +00:00
parent cc14c60736
commit 23576ff01e
12 changed files with 135 additions and 17 deletions

3
.gitignore vendored
View file

@ -1,2 +1,3 @@
**/bin **/bin
**/obj **/obj
**/appsettings.local.json

28
.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,28 @@
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/test/ContactForm.Tests/bin/Debug/netcoreapp2.1/ContactForm.Tests.dll",
"args": [],
"cwd": "${workspaceFolder}/test/ContactForm.Tests",
// For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window
"console": "internalConsole",
"stopAtEntry": false,
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
,]
}

15
.vscode/tasks.json vendored Normal file
View file

@ -0,0 +1,15 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/test/ContactForm.Tests/ContactForm.Tests.csproj"
],
"problemMatcher": "$msCompile"
}
]
}

View file

@ -12,5 +12,5 @@ This function is based off of my [lamda-dotnet-console](https://github.com/hyett
``` ```
cd src/ContactForm cd src/ContactForm
dotnet lambda deploy-function dotnet lambda deploy-function ContactForm
``` ```

View file

@ -1,4 +1,13 @@
using System; using System;
using System.Text;
using System.Threading.Tasks;
using ContactForm.Models;
using MailKit.Net.Smtp;
using MimeKit;
using MimeKit.Text;
using Serilog; using Serilog;
@ -20,12 +29,37 @@ namespace ContactForm
throw new ArgumentNullException(nameof(settings)); throw new ArgumentNullException(nameof(settings));
} }
public string Run(string input) public async Task Run(ContactRequest input)
{ {
_logger.Information("Lambda Function Starting"); var emailBody = new StringBuilder();
var result = $"{_settings.Prefix}{input?.ToUpper()}"; emailBody.AppendLine($"Name: {input.Name}");
_logger.Information("Lambda Function Finished"); emailBody.AppendLine($"Email: {input.Email}");
return result; emailBody.AppendLine($"Phone: {input.Phone}");
emailBody.AppendLine($"Website: {input.Website}");
emailBody.AppendLine($"Message: {input.Body}");
await SendEmail(emailBody.ToString());
}
public async Task SendEmail(string body)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Contact Form", _settings.EmailFrom));
message.To.Add(new MailboxAddress(_settings.EmailTo));
message.Subject = "Contact Request";
message.Body = new TextPart(TextFormat.Text)
{
Text = body
};
using(var client = new SmtpClient())
{
client.Connect(_settings.Host, _settings.Port, _settings.Port == 465);
client.AuthenticationMechanisms.Remove("XOAUTH2");
await client.AuthenticateAsync(_settings.Username, _settings.Password);
await client.SendAsync(message);
await client.DisconnectAsync(true);
}
} }
} }
} }

View file

@ -18,8 +18,11 @@
<PackageReference Include="Serilog.Extensions.Logging" Version="2.0.2"/> <PackageReference Include="Serilog.Extensions.Logging" Version="2.0.2"/>
<PackageReference Include="Serilog.Settings.Configuration" Version="3.0.1"/> <PackageReference Include="Serilog.Settings.Configuration" Version="3.0.1"/>
<PackageReference Include="Serilog.Sinks.Seq" Version="4.0.0"/> <PackageReference Include="Serilog.Sinks.Seq" Version="4.0.0"/>
<PackageReference Include="MimeKit" Version="2.1.0"/>
<PackageReference Include="MailKit" Version="2.1.0.3"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="appsettings.json" CopyToPublishDirectory="Always" CopyToOutputDirectory="PreserveNewest"/> <None Include="appsettings.json" CopyToPublishDirectory="Always" CopyToOutputDirectory="PreserveNewest"/>
<None Include="appsettings.local.json" CopyToPublishDirectory="PreserveNewest" CopyToOutputDirectory="PreserveNewest"/>
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -6,6 +6,8 @@ using System.Threading.Tasks;
using Amazon.Lambda.Core; using Amazon.Lambda.Core;
using ContactForm.Models;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@ -29,11 +31,12 @@ namespace ContactForm
/// <param name="input"></param> /// <param name="input"></param>
/// <param name="context"></param> /// <param name="context"></param>
/// <returns>string</returns> /// <returns>string</returns>
public string FunctionHandler(string input, ILambdaContext context) public string FunctionHandler(ContactRequest input, ILambdaContext context)
{ {
var configuration = new ConfigurationBuilder() var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory()) .SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional : false, reloadOnChange : true) .AddJsonFile("appsettings.json", optional : false, reloadOnChange : true)
.AddJsonFile("appsettings.local.json", optional : true, reloadOnChange : true)
.AddEnvironmentVariables(prefix: "LAMBDA_") .AddEnvironmentVariables(prefix: "LAMBDA_")
.Build(); .Build();
@ -50,9 +53,12 @@ namespace ContactForm
ConfigureServices(serviceCollection); ConfigureServices(serviceCollection);
var serviceProvider = serviceCollection.BuildServiceProvider(); var serviceProvider = serviceCollection.BuildServiceProvider();
var result = serviceProvider.GetService<App>().Run(input); var appService = serviceProvider.GetService<App>();
appService.Run(input).GetAwaiter().GetResult();
Log.CloseAndFlush(); Log.CloseAndFlush();
return result; return "OK";
} }
private void ConfigureServices(IServiceCollection serviceCollection) private void ConfigureServices(IServiceCollection serviceCollection)

View file

@ -0,0 +1,11 @@
namespace ContactForm.Models
{
public class ContactRequest
{
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Website { get; set; }
public string Body { get; set; }
}
}

View file

@ -2,6 +2,11 @@ namespace ContactForm
{ {
public class AppSettings public class AppSettings
{ {
public string Prefix { get; set; } public string EmailFrom { get; set; }
public string EmailTo { get; set; }
public string Host { get; set; }
public int Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
} }
} }

View file

@ -1,6 +1,11 @@
{ {
"App": { "App": {
"Prefix": "Test" "EmailFrom": "sender@example.com",
"EmailTo": "hello@example.com",
"Host": "smtp.example.com",
"Port": 465,
"Username": "email-username",
"Password": "email-password"
}, },
"Serilog": { "Serilog": {
"Using": ["Serilog.Sinks.Seq"], "Using": ["Serilog.Sinks.Seq"],

View file

@ -19,5 +19,6 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="appsettings.json" CopyToPublishDirectory="Always" CopyToOutputDirectory="PreserveNewest"/> <None Include="appsettings.json" CopyToPublishDirectory="Always" CopyToOutputDirectory="PreserveNewest"/>
<None Include="appsettings.local.json" CopyToPublishDirectory="PreserveNewest" CopyToOutputDirectory="PreserveNewest"/>
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -7,6 +7,7 @@ using Amazon.Lambda.Core;
using Amazon.Lambda.TestUtilities; using Amazon.Lambda.TestUtilities;
using ContactForm; using ContactForm;
using ContactForm.Models;
using Xunit; using Xunit;
@ -15,15 +16,23 @@ namespace ContactForm.Tests
public class FunctionTest public class FunctionTest
{ {
[Fact] [Fact]
public void TestToUpperFunction() public void TestOKReturned()
{ {
// Invoke the lambda function and confirm the string was upper cased.
var function = new Function(); var function = new Function();
var context = new TestLambdaContext(); var context = new TestLambdaContext();
var upperCase = function.FunctionHandler("hello world", context);
Assert.Equal("TestHELLO WORLD", upperCase); var contactRequest = new ContactRequest()
{
Name = "James Smith",
Email = "hello@example.com",
Phone = "01234567",
Website = "https://www.example.com",
Body = "This is a message"
};
var upperCase = function.FunctionHandler(contactRequest, context);
Assert.Equal("OK", upperCase);
} }
} }
} }