Git Product home page Git Product logo

a-patel / litexemail Goto Github PK

View Code? Open in Web Editor NEW
8.0 3.0 1.0 142 KB

LiteXEmail is simple yet powerful and very high-performance sms mechanism and incorporating both synchronous and asynchronous usage with some advanced usages which can help us to handle sending email more easier!

License: MIT License

email emailhelper smtp mailkit sendinblue mailchimp mailgun sendgrid nuget amazonses

litexemail's Introduction

LiteXEmail

LiteXEmail is simple yet powerful and very high-performance email message sending mechanism and incorporating both synchronous and asynchronous usage with some advanced usages which can help us to handle sending email more easier!

Provide email message service for ASP.NET Core (2.0 and later) applications.

Small library to abstract email message functionalities. Quick setup for any email message provider and very simple wrapper for the widely used email providers. LiteXEmail uses the least common denominator of functionality between the supported providers to send email messages solution. Abstract interface to implement any kind of basic email message services. Having a default/generic implementation to wrap the SMTP, SendGrid, MailKit, Mailgun, MailChimp, AmazonSES, SendinBlue. An email message abstraction.

Very simple configuration in advanced ways. Purpose of this package is to bring a new level of ease to the developers who deal with different email message provider integration with their system and implements many advanced features. You can also write your own and extend it also extend existing providers. Easily migrate or switch between one to another provider with no code breaking changes.

LiteXEmail is an interface to unify the programming model for various email providers. The Core library contains all base interfaces and tools. One should install at least one other LiteXEmail package to get email message implementation.

Email Providers ๐Ÿ“š

Features ๐Ÿ“Ÿ

  • Attachment
  • ReplyTo
  • Cc, Bcc (multiple)
  • Async compatible
  • Thread safe, concurrency ready
  • Obsolete sync methods
  • Multiple provider support (using provider factory)
  • Interface based API to support the test driven development and dependency injection
  • Leverages a provider model on top of ILiteXEmailSender under the hood and can be extended with your own implementation

Basic Usage ๐Ÿ“„

Step 1 : Install the package ๐Ÿ“ฆ

Choose one kinds of email provider type that you needs and install it via Nuget. To install LiteXEmail, run the following command in the Package Manager Console

PM> Install-Package LiteX.Email
PM> Install-Package LiteX.Email.SendGrid
PM> Install-Package LiteX.Email.AmazonSES
PM> Install-Package LiteX.Email.MailKit
PM> Install-Package LiteX.Email.Mailgun

Step 2 : Configuration ๐Ÿ”จ

Different types of email provider have their own way to config. Here are samples that show you how to config.

2.1 : AppSettings
{
  //LiteX Smtp settings
  "SmtpConfig": {
    "Email": "--- REPLACE WITH YOUR Email ---",
    "DisplayName": "--- REPLACE WITH YOUR DisplayName ---",
    "Host": "--- REPLACE WITH Host Host ---",
    "Port": 587, //"--- REPLACE WITH YOUR Port (int) ---",
    "Username": "--- REPLACE WITH YOUR Username ---",
    "Password": "--- REPLACE WITH YOUR Password ---",
    "EnableSsl": true, //"--- REPLACE WITH YOUR EnableSsl (boolean) ---",
    "UseDefaultCredentials": false, //"--- REPLACE WITH YOUR UseDefaultCredentials (boolean) ---",
    "EnableLogging": true
  },

  //LiteX SendGrid settings
  "SendGridConfig": {
    "SendGridApiKey": "--- REPLACE WITH YOUR SendGridApiKey ---",
    "EnableLogging": true
  },

  //LiteX AmazonSES settings
  "AmazonSESConfig": {
    "AmazonSESAccessKey": "--- REPLACE WITH YOUR AmazonSESAccessKey ---",
    "AmazonSESSecretKey": "--- REPLACE WITH YOUR AmazonSESSecretKey ---",
    "AmazonRegion": "--- REPLACE WITH YOUR AmazonRegion ---",
    "EnableLogging": true
  },

  //LiteX MailKit settings
  "MailKitConfig": {
    "Email": "--- REPLACE WITH YOUR Email ---",
    "DisplayName": "--- REPLACE WITH YOUR DisplayName ---",
    "Host": "--- REPLACE WITH Host Host ---",
    "Port": 587, //"--- REPLACE WITH YOUR Port (int) ---",
    "Username": "--- REPLACE WITH YOUR Username ---",
    "Password": "--- REPLACE WITH YOUR Password ---",
    "EnableSsl": false,
    "UseDefaultCredentials": false,
    "EnableLogging": true
  },

  //LiteX Mailgun settings
  "MailgunConfig": {
    "ApiKey": "api:key-fakeapikey",
    "ApiBaseUri": "https://api.mailgun.net/v3/",
    "RequestUri": "fakesandbox.mailgun.org/messages",
    "From": "[email protected]",
    "EnableLogging": true
  },

  //LiteX MailChimp settings
  "MailChimpConfig": {
    "MailChimpApiKey": "--- REPLACE WITH YOUR MailChimpApiKey ---",
    "EnableLogging": true
  },

  //LiteX SendinBlue settings
  "SendinBlueConfig": {
    "SendinBlueApiKey": "--- REPLACE WITH YOUR  ---",
    "EnableLogging": true
  }
}
2.2 : Configure Startup Class
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        #region LiteX Email (SMTP)

        // 1. Use default configuration from appsettings.json's 'SmtpConfig'
        services.AddLiteXSmtpEmail();

        //OR
        // 2. Load configuration settings using options.
        services.AddLiteXSmtpEmail(option =>
        {
            option.Host = "";
            option.Username = "";
            option.Password = "";
            option.Port = 443;
            option.Email = "";
            option.EnableSsl = true;
            option.UseDefaultCredentials = true;
            option.DisplayName = "";
            option.EnableLogging = true;
        });

        //OR
        // 3. Load configuration settings on your own.
        // (e.g. appsettings, database, hardcoded)
        var smtpConfig = new SmtpConfig()
        {
            Host = "",
            Username = "",
            Password = "",
            Port = 443,
            Email = "",
            EnableSsl = true,
            UseDefaultCredentials = true,
            DisplayName = "",
            EnableLogging = true
        };
        services.AddLiteXSmtpEmail(smtpConfig);

        #endregion

        #region LiteX Email (SendGrid)

        // 1. Use default configuration from appsettings.json's 'SendGridConfig'
        services.AddLiteXSendGridEmail();

        //OR
        // 2. Load configuration settings using options.
        services.AddLiteXSendGridEmail(option =>
        {
            option.SendGridApiKey = "";
            option.EnableLogging = true;
        });

        //OR
        // 3. Load configuration settings on your own.
        // (e.g. appsettings, database, hardcoded)
        var sendGridConfig = new SendGridConfig()
        {
            SendGridApiKey = "",
            EnableLogging = true
        };
        services.AddLiteXSendGridEmail(sendGridConfig);

        #endregion

        #region LiteX Email (MailKit)

        // 1. Use default configuration from appsettings.json's 'MailKitConfig'
        services.AddLiteXMailKitEmail();

        //OR
        // 2. Load configuration settings using options.
        services.AddLiteXMailKitEmail(option =>
        {
            option.Host = "";
            option.Username = "";
            option.Password = "";
            option.Port = 443;
            option.Email = "";
            option.EnableSsl = true;
            option.UseDefaultCredentials = true;
            option.DisplayName = "";
            option.EnableLogging = true;
        });

        //OR
        // 3. Load configuration settings on your own.
        // (e.g. appsettings, database, hardcoded)
        var mailKitConfig = new MailKitConfig()
        {
            Host = "",
            Username = "",
            Password = "",
            Port = 443,
            Email = "",
            EnableSsl = true,
            UseDefaultCredentials = true,
            DisplayName = "",
            EnableLogging = true
        };
        services.AddLiteXMailKitEmail(mailKitConfig);

        #endregion

        #region LiteX Email (AmazonSES)

        // 1. Use default configuration from appsettings.json's 'AmazonSESConfig'
        services.AddLiteXAmazonSESEmail();

        //OR
        // 2. Load configuration settings using options.
        services.AddLiteXAmazonSESEmail(option =>
        {
            option.AmazonSESAccessKey = "";
            option.AmazonSESSecretKey = "";
            option.AmazonRegion = "";
            option.EnableLogging = true;
        });

        //OR
        // 3. Load configuration settings on your own.
        // (e.g. appsettings, database, hardcoded)
        var amazonSESConfig = new AmazonSESConfig()
        {
            AmazonSESAccessKey = "",
            AmazonSESSecretKey = "",
            AmazonRegion = "",
            EnableLogging = true
        };
        services.AddLiteXAmazonSESEmail(amazonSESConfig);

        #endregion

        #region LiteX Email (Mailgun)

        // 1. Use default configuration from appsettings.json's 'MailgunConfig'
        services.AddLiteXMailgunEmail();

        //OR
        // 2. Load configuration settings using options.
        services.AddLiteXMailgunEmail(option =>
        {
            option.ApiKey = "";
            option.ApiBaseUri = "";
            option.RequestUri = "";
            option.From = "";
            option.EnableLogging = true;
        });

        //OR
        // 3. Load configuration settings on your own.
        // (e.g. appsettings, database, hardcoded)
        var mailgunConfig = new MailgunConfig()
        {
            ApiKey = "",
            ApiBaseUri = "",
            RequestUri = "",
            From = "",
            EnableLogging = true
        };
        services.AddLiteXMailgunEmail(mailgunConfig);

        #endregion


        // add logging (optional)
        services.AddLiteXLogging();
    }
}

Step 3 : Use in Controller or Business layer ๐Ÿ“

/// <summary>
/// Customer controller
/// </summary>
[Route("api/[controller]")]
public class CustomerController : Controller
{
    #region Fields

    private readonly ILiteXEmailSender _emailSender;

    #endregion

    #region Ctor

    /// <summary>
    /// Ctor
    /// </summary>
    /// <param name="emailSender"></param>
    public CustomerController(ILiteXEmailSender emailSender)
    {
        _emailSender = emailSender;
    }

    #endregion

    #region Methods

    /// <summary>
    /// Get Email Provider Type
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [Route("get-email-provider-type")]
    public IActionResult GetEmailProviderType()
    {
        return Ok(_emailSender.EmailProviderType.ToString());
    }

    /// <summary>
    /// Send Email 
    /// </summary>
    /// <param name="emailMessage">Email Message</param>
    /// <returns></returns>
    [HttpPost]
    [Route("send-email")]
    public async Task<IActionResult> SendEmailToCustomer(EmailMessage emailMessage)
    {
        var message = EnsureValidEmailMessage(emailMessage);

        var subject = message.Subject;
        var body = message.Body;
        var fromAddress = message.FromAddress;
        var fromName = message.FromName;
        var toAddress = message.ToAddress;
        var toName = message.ToName;
        var replyToAddress = message.ReplyToAddress;
        var replyToName = message.ReplyToName;
        var isHtml = message.IsHtml;
        var mailPriority = message.MailPriority;

        IEnumerable<string> bcc = new List<string>() { message.Bcc };
        IEnumerable<string> cc = new List<string>() { message.Cc };

        // async
        var result = await _emailSender.SendEmailAsync(subject, body, fromAddress, fromName, toAddress, toName, replyToAddress, replyToName, bcc, cc, isHtml: isHtml, priority: mailPriority);

        //// sync
        //var result = _emailSender.SendEmail(subject, body, fromAddress, fromName, toAddress, toName, replyToAddress, replyToName, bcc, cc, isHtml: isHtml, priority: mailPriority);
        //var result = _emailSender.SendEmail(subject, body, fromAddress, fromName, toAddress, toName, replyToAddress, replyToName, bcc, cc, isHtml: isHtml, priority: mailPriority);

        return Ok(result);
    }

    /// <summary>
    /// Send email with attachment
    /// </summary>
    /// <param name="emailMessage">Email Message</param>
    /// <param name="file">Attachment</param>
    /// <returns></returns>
    [HttpPost]
    [Route("send-email-with-attachment")]
    [AddSwaggerFileUploadButton]
    public async Task<IActionResult> SendEmailToCustomerWithAttachment(EmailMessage emailMessage, IFormFile file)
    {
        var message = EnsureValidEmailMessage(emailMessage);

        var subject = message.Subject;
        var body = message.Body;
        var fromAddress = message.FromAddress;
        var fromName = message.FromName;
        var toAddress = message.ToAddress;
        var toName = message.ToName;
        var replyToAddress = message.ReplyToAddress;
        var replyToName = message.ReplyToName;
        var isHtml = message.IsHtml;
        var mailPriority = message.MailPriority;

        IEnumerable<string> bcc = new List<string>() { message.Bcc };
        IEnumerable<string> cc = new List<string>() { message.Cc };
        List<Attachment> attachments = new List<Attachment>
            {
                new Attachment()
                {
                    ContentType = file?.ContentType,
                    Filename = file?.FileName,
                    Data = file?.OpenReadStream()
                }
            };

        // async
        var result = await _emailSender.SendEmailAsync(subject, body, fromAddress, fromName, toAddress, toName, replyToAddress, replyToName, bcc, cc, attachments: attachments, isHtml: isHtml, priority: mailPriority);

        //// sync
        //var result = _emailSender.SendEmail(subject, body, fromAddress, fromName, toAddress, toName, replyToAddress, replyToName, bcc, cc, attachments: attachments, isHtml: isHtml, priority: mailPriority);
        //var result = _emailSender.SendEmail(subject, body, fromAddress, fromName, toAddress, toName, replyToAddress, replyToName, bcc, cc, isHtml: isHtml, priority: mailPriority);

        return Ok(result);
    }

    #endregion

    #region Utilities

    private EmailMessage EnsureValidEmailMessage(EmailMessage emailMessage)
    {
        var message = new EmailMessage()
        {
            Subject = emailMessage.Subject ?? "LiteX Email!",
            Body = emailMessage.Body ?? "Welcome to LiteX Email Service!",
            FromAddress = emailMessage.FromAddress ?? "[email protected]",
            FromName = emailMessage.FromName ?? "LiteX",
            ToAddress = emailMessage.ToAddress ?? "[email protected]",
            ToName = emailMessage.ToName ?? "Aashish Patel",
            ReplyToAddress = emailMessage.ReplyToAddress ?? "[email protected]",
            ReplyToName = emailMessage.ReplyToName ?? "Ashish Patel",
            Bcc = emailMessage.FromAddress ?? "[email protected]",
            Cc = emailMessage.FromAddress ?? "[email protected]",
            IsHtml = emailMessage.IsHtml,
            MailPriority = emailMessage.MailPriority,
        };

        message.Body = $"{message.Body} - Provider: {_emailSender.EmailProviderType.ToString()}";

        return message;
    }

    #endregion
}

Todo List ๐Ÿ“‹

Storage Providers

  • Smtp
  • SendGrid
  • AmazonSES
  • MailKit
  • Mailgun
  • MailJet
  • MailChimp
  • SendinBlue
  • ElasticEmail

Basic Storage API

  • SendEmail

Coming soon

  • .NET Standard 2.1 support
  • .NET 5.0 support
  • Remove sync methods
  • Response Result
  • Bulk Email

Give a Star! โญ

Feel free to request an issue on github if you find bugs or request a new feature. Your valuable feedback is much appreciated to better improve this project. If you find this useful, please give it a star to show your support for this project.

Support โ˜Ž๏ธ

Reach out to me at one of the following places!

Author ๐Ÿ‘ฆ

Connect with me
Linkedin Website Medium NuGet GitHub Microsoft Facebook Twitter Instagram Tumblr
linkedin website medium nuget github microsoft facebook twitter instagram tumblr

Donate ๐Ÿ’ต

If you find this project useful โ€” or just feeling generous, consider buying me a beer or a coffee. Cheers! ๐Ÿป โ˜•

PayPal BMC Patreon
PayPal Buy Me A Coffee Patreon

License ๐Ÿ”’

This project is licensed under the MIT License - see the LICENSE file for details.

litexemail's People

Contributors

a-patel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

codefork

litexemail's Issues

There is no AddLitexEmail Method

Hello i am trying this library to my code but when call services.AddLiteXEmail(); in ConfigureService method ide cannot find this method i am using Litex.Email 9.0.0 at .net 5 on vs for mac

Upgrade to .NET Core 3.x

Upgrade all LiteX Email packages to .NET Core 3.x
Upgrade all dependent Microsoft packages to .NET Core 3.x
Upgrade all dependent packages (SDKs) to the latest version

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.