LNT.MailService
1.2.0
dotnet add package LNT.MailService --version 1.2.0
NuGet\Install-Package LNT.MailService -Version 1.2.0
<PackageReference Include="LNT.MailService" Version="1.2.0" />
<PackageVersion Include="LNT.MailService" Version="1.2.0" />
<PackageReference Include="LNT.MailService" />
paket add LNT.MailService --version 1.2.0
#r "nuget: LNT.MailService, 1.2.0"
#:package LNT.MailService@1.2.0
#addin nuget:?package=LNT.MailService&version=1.2.0
#tool nuget:?package=LNT.MailService&version=1.2.0
LNT.MailService
A simple and efficient email sending library for ASP.NET Core applications, built on top of MailKit and MimeKit. This library provides a clean abstraction for sending emails with minimal configuration and easy dependency injection integration.
New in Version 1.2.0
- Support connect on port 465 (SSL)
Features
- 🚀 Easy integration with ASP.NET Core dependency injection
- 📧 Support for HTML email content
- 🔐 Secure SMTP authentication with TLS
- 📝 Built-in logging support
- ⚡ Async/await pattern for better performance
- 🎯 Simple and intuitive API
- 🛡️ Exception handling with detailed logging
Installation
Install the package via NuGet Package Manager:
dotnet add package LNT.MailService
Or via Package Manager Console:
Install-Package LNT.MailService
Or add it directly to your .csproj file:
<PackageReference Include="LNT.MailService" Version="1.2.0" />
Requirements
- .NET 8.0 or later
- ASP.NET Core application
Quick Start
1. Configure Mail Settings
Add the mail configuration to your appsettings.json:
{
"MailSettings": {
"Mail": "your-email@example.com",
"DisplayName": "Your Application Name",
"Password": "your-app-password",
"Host": "smtp.gmail.com", # For Gmail, use smtp.gmail.com
"Port": 587,
"UseSSL": false # false for TLS, true for SSL on port 465
}
}
Note: You'll need to use an App Password for Gmail.
2. Register the Service
In your Program.cs, register the mail service:
using MailSender;
var builder = WebApplication.CreateBuilder(args);
// Add mail service
builder.Services.AddMailService(builder.Configuration);
var app = builder.Build();
app.Run();
3. Use the Service
Inject IMailSender into your controllers, services, or any other class:
using MailSender;
using MailSender.Models;
public class NotificationService
{
private readonly IMailSender _mailSender;
public NotificationService(IMailSender mailSender)
{
_mailSender = mailSender;
}
public async Task SendWelcomeEmail(string recipientEmail)
{
var mailContent = new MailContent
{
To = recipientEmail,
Subject = "Welcome to Our Service!",
Body = "<h1>Welcome!</h1><p>Thank you for joining us.</p>"
};
bool result = await _mailSender.SendMailAsync(mailContent);
if (result)
{
Console.WriteLine("Email sent successfully!");
}
else
{
Console.WriteLine("Failed to send email.");
}
}
}
Configuration Options
MailSettings (json configuration section)
| Property | Type | Required | Description |
|---|---|---|---|
Mail |
string | Yes | The email address to send from |
DisplayName |
string | Yes | The display name for the sender |
Password |
string | Yes | The email account password or app-specific password |
Host |
string | Yes | SMTP server host (e.g., smtp.gmail.com) |
Port |
int | Yes | SMTP server port (typically 587 for TLS) |
UseSSL |
bool | No (default: true) | Whether to use SSL/TLS for the connection |
MailContent
| Property | Type | Required | Description |
|---|---|---|---|
To |
string | Yes | Recipient email address |
Subject |
string | Yes | Email subject line |
Body |
string | Yes | Email body content (supports HTML) |
Advanced Usage
Sending HTML Emails
The library fully supports HTML content in email bodies:
var mailContent = new MailContent
{
To = "recipient@example.com",
Subject = "Monthly Newsletter",
Body = @"
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; }
.header { background-color: #4CAF50; color: white; padding: 10px; }
</style>
</head>
<body>
<div class='header'>
<h1>Newsletter</h1>
</div>
<p>Here's your monthly update...</p>
</body>
</html>
"
};
await _mailSender.SendMailAsync(mailContent);
Using in Controllers
using Microsoft.AspNetCore.Mvc;
using MailSender;
[ApiController]
[Route("api/[controller]")]
public class EmailController : ControllerBase
{
private readonly IMailSender _mailSender;
private readonly ILogger<EmailController> _logger;
public EmailController(IMailSender mailSender, ILogger<EmailController> logger)
{
_mailSender = mailSender;
_logger = logger;
}
[HttpPost("send")]
public async Task<IActionResult> SendEmail([FromBody] MailContent mailContent)
{
var result = await _mailSender.SendMailAsync(mailContent);
if (result)
{
return Ok(new { message = "Email sent successfully" });
}
return BadRequest(new { message = "Failed to send email" });
}
}
Security Best Practices
Never commit credentials: Store sensitive information in user secrets during development:
dotnet user-secrets set "MailSettings:Password" "your-password"Use environment variables: In production, use environment variables or secure vaults:
export MailSettings__Password="your-password"Use App Passwords: For services like Gmail, use app-specific passwords instead of your main account password.
Encrypted Configuration: Consider using Azure Key Vault or similar services for production environments.
Logging
The library includes built-in logging support. Successful email sends and errors are automatically logged using the provided ILogger<MailSender>.
To see the logs, ensure logging is configured in your appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"MailSender": "Information"
}
}
}
Troubleshooting
Common Issues
Authentication Failed
- Verify your email and password are correct
- For Gmail, ensure you're using an App Password
- Check if "Less secure app access" is enabled (if applicable)
Connection Timeout
- Verify the SMTP host and port are correct
- Check if your firewall is blocking the connection
- Ensure your hosting provider allows outbound SMTP connections
Email Not Received
- Check the recipient's spam/junk folder
- Verify the recipient email address is correct
- Check your email provider's sending limits
Dependencies
This library uses the following packages:
- MailKit (v4.15.1)
- MimeKit (v4.15.1)
- Microsoft.Extensions.* (v8.0.0)
License
This project is licensed under the MIT License.
Support
For issues, questions, or contributions, please visit the project repository or contact the author.
Author
LƯƠNG NHẬT TRƯỜNG
Changelog
Version 1.2.0
- Initial release
- Basic email sending functionality
- Dependency injection support
- HTML email support
- Built-in logging
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- MailKit (>= 4.15.1)
- Microsoft.Extensions.Configuration.Abstractions (>= 8.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Options (>= 8.0.0)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 8.0.0)
- MimeKit (>= 4.15.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.