{"id":1552,"date":"2018-12-04T18:00:00","date_gmt":"2018-12-04T18:00:00","guid":{"rendered":"https:\/\/xplicity.com\/?p=1552"},"modified":"2025-01-03T14:44:20","modified_gmt":"2025-01-03T11:44:20","slug":"serverless-email-sender-using-openfaas-and-net-core","status":"publish","type":"post","link":"https:\/\/xplicity.com\/serverless-email-sender-using-openfaas-and-net-core\/","title":{"rendered":"Serverless email sender using OpenFaaS and .NET Core"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Since popularity of&nbsp;serverless programming increasingly growing, I decided to look into it more detailed. From the first glance, we can see two main platforms\u200a\u2014\u200aAmazon AWS Lambda and Azure Functions. These solutions have a whole infrastructure around them starting with monitoring tools, API gateway service, serverless databases to triggers from message queues, databases or even file storage. However, these solutions are not perfect because our functions are more likely to be closely coupled to selected platform technology stack. Because of this problem I decided to look for other solutions and sharing one of them with you.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">While looking for alternative I found&nbsp;<a href=\"https:\/\/github.com\/openfaas\" target=\"_blank\" rel=\"noreferrer noopener\">OpenFaaS<\/a>, which is a serverless platform made using Docker infrastructure. It allows deploying functions to Kubernetes or Docker Swarm clusters. Furthermore, it\u2019s Docker-based technology we can run technology inside a container and we will be able to integrate it into OpenFaaS system. So, for testing purposes I decided to create a simple email sender application, that would be able to scale on demand by leveraging the OpenFaaS platform.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"16dc\"><strong>PREPARING THE ENVIRONMENT<\/strong><\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Install&nbsp;<a href=\"https:\/\/www.docker.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">Docker<\/a><\/li>\n\n\n\n<li>Initialize Docker Swarm\u2019s master node. (Run command&nbsp;docker swarm init).<\/li>\n\n\n\n<li>Install the&nbsp;<a href=\"https:\/\/docs.openfaas.com\/cli\/install\/\" target=\"_blank\" rel=\"noreferrer noopener\">OpenFaaS CLI<\/a><\/li>\n\n\n\n<li>Download OpenFaaS function templates. (Run command&nbsp;faas-cli template pull https:\/\/github.com\/openfaas\/templates).<\/li>\n\n\n\n<li>Clone&nbsp;<a href=\"https:\/\/github.com\/openfaas\/faas\" target=\"_blank\" rel=\"noreferrer noopener\">OpenFaaS repository<\/a>&nbsp;and deploy the stack (run deploy_stack.sh file from the cloned repository)<\/li>\n\n\n\n<li>Deploy_stack.sh script will generate admin credentials, that we will use in OpenFaaS CLI and UI.<\/li>\n\n\n\n<li>Login to CLI using&nbsp;faas-cli login &#8211;username &#8220;generated password&#8221; &#8211;password &#8220;generated password&#8221;<\/li>\n\n\n\n<li>Visit\u00a0<a rel=\"noreferrer noopener\" href=\"http:\/\/localhost:8080\/\" target=\"_blank\">OpenFaaS UI<\/a>\u00a0to check if everything works as expected.<\/li>\n<\/ol>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"808\" height=\"280\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb1ee3ef50.png\" alt=\"\" class=\"wp-image-1554\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb1ee3ef50.png 808w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb1ee3ef50-300x104.png 300w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb1ee3ef50-768x266.png 768w\" sizes=\"auto, (max-width: 808px) 100vw, 808px\" \/><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">Currently, there are no deployed functions, but we will add one in a moment.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7736\">CREATING A NEW OPENFAAS&nbsp;FUNCTION<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">So at first, we will create a new function using OpenFaaS CLI command&nbsp;faas-cli new EmailSender &#8211;lang csharp. This command will create a&nbsp;EmailSender.yml&nbsp;file and a new directory named&nbsp;EmailSender&nbsp;that contains three generated files:&nbsp;Function.csproj,&nbsp;FunctionHandler.cs&nbsp;and&nbsp;gitignore.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">All the functions that need to be built and deployed to OpenFaaS cluster must be declared in\u00a0EmailSender.yml\u00a0file:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>provider:\n  name: faas\n  gateway: http:\/\/localhost:8080\nfunctions:\n  EmailSender:\n    lang: csharp\n    handler: .\/EmailSender\n    image: emailsender<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Those who are accustomed to Docker might ask where is the function\u2019s DockerFile, it\u2019s declared in&nbsp;templates&nbsp;and copied to&nbsp;build&nbsp;directory when running a&nbsp;faas-cli build&nbsp;command. Although, if you want you can declare your own DockerFile.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Those who are accustomed to Docker might ask where is the function\u2019s DockerFile, it\u2019s declared in&nbsp;templates&nbsp;and copied to&nbsp;build&nbsp;directory when running a&nbsp;faas-cli build&nbsp;command. Although, if you want you can declare your own DockerFile.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now we can start building email sender function. Let\u2019s open\u00a0EmailSender\/FunctionHandler.cs\u00a0file and modify it:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using System;\nusing System.Net;\nusing System.Net.Mail;\nusing Newtonsoft.Json;\nnamespace Function\n{\n  public class FunctionHandler\n  {\n    public string Handle(string input)\n    {\n      if (string.IsNullOrWhiteSpace(input)) {\n        throw new ArgumentNullException(nameof(input));\n      }\n      var newEmail = JsonConvert.DeserializeObject(input);\n      var smtpSettings = GetSmtpSettings();\n      string result;\n      try\n      {\n        var from = new MailAddress(smtpSettings.SmtpUsername, newEmail.Author);\n        var to = new MailAddress(newEmail.Receiver);\n        var newEmailMessage = new MailMessage(from, to) {\n          Priority = MailPriority.High,\n          Body = newEmail.Content,\n          Subject = newEmail.Title\n        };\n        using (var smtp = new SmtpClient(smtpSettings.SmtpHost, smtpSettings.SmtpPort))\n        {\n           smtp.Credentials = new NetworkCredential(smtpSettings.SmtpUsername, smtpSettings.SmtpPassword);\n           smtp.EnableSsl = true;\n           smtp.Send(newEmailMessage);\n        }\n        result = $\"Succesfully send a message, payload:{JsonConvert.SerializeObject(newEmail)}\";\n        }\n      catch (Exception ex)\n      {\n        result = ex.Message;\n      }\n      return result;\n    }\n    private static SmtpSettings GetSmtpSettings()\n    {\n      int GetSmtpPort(string port) =&gt; port == null ? 587 : Convert.ToInt32(port);\n      var smtpHost = Environment.GetEnvironmentVariable(\"SmtpHost\");\n      var smtpPassword = Environment.GetEnvironmentVariable(\"SmtpPassword\");\n      var smtpPort = GetSmtpPort(Environment.GetEnvironmentVariable(\"SmtpPort\"));\n      var smtpUsername = Environment.GetEnvironmentVariable(\"SmtpUsername\");\n      return new SmtpSettings {\n        SmtpHost = smtpHost,\n        SmtpPassword = smtpPassword,\n        SmtpPort = smtpPort,\n        SmtpUsername = smtpUsername\n      };\n    }\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For making this code work we will create two additional files.&nbsp;NewEmail.cs&nbsp;file contains&nbsp;NewEmail&nbsp;class that declares properties which we need to pass to our function.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>namespace Function\n{\n  public class NewEmail\n  {\n    public string Author { get; set; }\n    public string Receiver { get; set; }\n    public string Title { get; set; }\n    public string Content { get; set; }\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Furthermore, we need to create&nbsp;SmtpSettings.cs&nbsp;file with&nbsp;SmtpSettings&nbsp;class which contains properties needed for an SMTP connection.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>namespace Function\n{\n  public class SmtpSettings\n  {\n    public string SmtpHost { get; set; }\n    public int SmtpPort { get; set; }\n    public string SmtpUsername { get; set; }\n    public string SmtpPassword { get; set; }\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, we need to modify&nbsp;EmailSender.yml&nbsp;file to provide SMTP settings through environment variables (I know it isn\u2019t safest option, but we can improve it later).<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>provider:\n  name: faas\n  gateway: http:\/\/localhost:8080\nfunctions:\n  EmailSender:\n    lang: csharp\n    handler: .\/EmailSender\n    image: emailsender\n    environment:\n      SmtpHost: smtp.gmail.com\n      SmtpPort: 587\n      SmtpUsername: your_username@gmail.com\n      SmtpPassword: your_password<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"774b\">DEPLOYING FUNCTION<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">At first we need to build newly created function, for that we can use&nbsp;faas-cli build -f .\/emailsender.yml&nbsp;command. After running this command we should see output similar to this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;0] &gt; Building: EmailSender.\nClearing temporary build folder: .\/build\/EmailSender\/\nPreparing .\/EmailSender\/ .\/build\/EmailSender\/function\nBuilding: emailsender with csharp template. Please wait..\nSending build context to Docker daemon  160.3kB\nStep 1\/20 : FROM microsoft\/dotnet:2.1-sdk as builder\n....\nStep 20\/20 : CMD &#91;\"fwatchdog\"]\n ---&gt; Running in 34af35ffc2cf\nRemoving intermediate container 34af35ffc2cf\n ---&gt; b757268b4502\nSuccessfully built b757268b4502\nSuccessfully tagged emailsender:latest<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, we can deploy our function to OpenFaaS cluster:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>faas-cli -action deploy -f .\/emailsender.yml\nDeploying: EmailSender.\nRemoving old function.\nDeployed.\nURL: http:\/\/localhost:8080\/function\/EmailSender<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now we should be able to see our newly created function in UI.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"823\" height=\"280\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb20035030.png\" alt=\"\" class=\"wp-image-1555\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb20035030.png 823w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb20035030-300x102.png 300w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb20035030-768x261.png 768w\" sizes=\"auto, (max-width: 823px) 100vw, 823px\" \/><\/figure>\n<\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"799b\">SENDING EMAILS USING THE CREATED&nbsp;FUNCTION<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">After the function is successfully deployed to OpenFaaS cluster we should be able to use it through HTTP Post method or via OpenFaaS user interface. Let\u2019s select our function and fill the request body with the following information.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"800\" height=\"473\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb20dd4b29.png\" alt=\"\" class=\"wp-image-1556\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb20dd4b29.png 800w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb20dd4b29-300x177.png 300w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb20dd4b29-768x454.png 768w\" sizes=\"auto, (max-width: 800px) 100vw, 800px\" \/><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">After we hit the invoke button, an email will be sent to the selected recipient. Furthermore, the invocation count will be increased so we can keep track of how many calls were made to this function. In case this function receives a lot of calls it will automatically scale from one up to twenty replicas (using default configuration).<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>echo SuperSecretPassword | docker secret create smtp-password -\ndocker secret ls\nID                          NAME\nri2keefoyrar92scrv9mmx0r2   api-key\nkfastke0gxtm9dnps40k3nrhn   basic-auth-password\ncip9t43z7t2ti8grfucz0v6a9   basic-auth-user\n3riiu97rac5ls0jr5778in7dy   smtp-password<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now we that created a docker secret for SMTP password we can see the main reason to extract this information from environment variables to docker secrets is that we cannot read this information, only the metadata about it.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>docker secret inspect 3riiu97rac5ls0jr5778in7dy\n&#91;\n    {\n        \"ID\": \"3riiu97rac5ls0jr5778in7dy\",\n        \"Version\": {\n            \"Index\": 283\n        },\n        \"CreatedAt\": \"2018-08-15T10:57:23.6925097Z\",\n        \"UpdatedAt\": \"2018-08-15T10:57:23.6925097Z\",\n        \"Spec\": {\n            \"Name\": \"smtp-password\",\n            \"Labels\": {}\n        }\n    }\n]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now we can extend code to read this information from \/var\/openfaas\/secrets location inside docker.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>private static SmtpSettings GetSmtpSettings()\n{\n    int GetSmtpPort(string port) =&gt; port == null ? 587 : Convert.ToInt32(port);\nvar smtpHost = Environment.GetEnvironmentVariable(\"SmtpHost\");\n    var smtpPassword = ReadSecret(\"smtp-password\");\n    var smtpPort = GetSmtpPort(Environment.GetEnvironmentVariable(\"SmtpPort\"));\n    var smtpUsername = Environment.GetEnvironmentVariable(\"SmtpUsername\");\n    return new SmtpSettings\n    {\n        SmtpHost = smtpHost,\n        SmtpPassword = smtpPassword,\n        SmtpPort = smtpPort,\n        SmtpUsername = smtpUsername\n    };\n}\nprivate static string ReadSecret(string secretName)\n{\n    return File.ReadAllText( ${SecretsLocation}\/{secretName}\").Trim();\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1a06\">ADDING AUTHORIZATION<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Lastly, we can add some basic authorization to our function with docker secrets. Let\u2019s create an api-key secret using these commands:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$APIKey = \"09f62255f206eea5ae0481feadc22d3092706b4a\"\necho $APIKey | docker secret create api-key -<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now let\u2019s add the additional method to authorize function calls.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>private static bool Authorize()\n{\n    var secret = ReadSecret(\"api-key\");\n    var headerAuth = Environment.GetEnvironmentVariable(\"Http_Authorization\");\n\n    bool result;\n    if (headerAuth == null || headerAuth != \"Bearer \" + secret)\n    {\n        result = false;\n    } else {\n        result = true;\n    }\n    return result;\n}\nbool result;\nif (headerAuth == null || headerAuth != \"Bearer \" + secret) {\n        result = false;\n    } else {\n        result = true;\n    }\nreturn result;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Let\u2019s try whether our authorization is working.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"602\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb21b6beab-1024x602.png\" alt=\"\" class=\"wp-image-1557\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb21b6beab-1024x602.png 1024w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb21b6beab-300x176.png 300w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb21b6beab-768x451.png 768w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb21b6beab.png 1200w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">Let\u2019s try to add our created Bearer token to Authorization request header and make a request through Postman.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"948\" height=\"562\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb226d2cc7.png\" alt=\"\" class=\"wp-image-1558\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb226d2cc7.png 948w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb226d2cc7-300x178.png 300w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5dadb226d2cc7-768x455.png 768w\" sizes=\"auto, (max-width: 948px) 100vw, 948px\" \/><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">Now, we can be sure that only authorized users can access and use this function.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">CONSLUSION<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">So that\u2019s it, we have created a serverless function that is not only able to send emails but also is able to automatically increase\/decrease the number of replicas depending on traffic through OpenFaaS platform.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">All the code discussed here can be found:<br><a href=\"https:\/\/github.com\/Skisas\/EmailSender\">https:\/\/github.com\/Skisas\/EmailSender<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Since popularity of&nbsp;serverless programming increasingly growing, I decided to look into it more detailed. From the first glance, we can see two main platforms\u200a\u2014\u200aAmazon AWS Lambda and Azure Functions. These solutions have a whole infrastructure around them starting with monitoring tools, API gateway service, serverless databases to triggers from message queues, databases or even file [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1553,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[],"class_list":["post-1552","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog"],"acf":[],"_links":{"self":[{"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/posts\/1552","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/comments?post=1552"}],"version-history":[{"count":1,"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/posts\/1552\/revisions"}],"predecessor-version":[{"id":1559,"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/posts\/1552\/revisions\/1559"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/media\/1553"}],"wp:attachment":[{"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/media?parent=1552"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/categories?post=1552"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/tags?post=1552"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}