Skip to content

Commit

Permalink
Merge pull request #13 from bentran1vn/Config/MailService
Browse files Browse the repository at this point in the history
Config/mail service
  • Loading branch information
bentran1vn authored Oct 10, 2024
2 parents 92ffb45 + 90605ac commit 6dad47f
Showing 10 changed files with 119 additions and 11 deletions.
1 change: 1 addition & 0 deletions MBS-COMMAND.API/Program.cs
Original file line number Diff line number Diff line change
@@ -73,6 +73,7 @@
builder.Services.AddServicesInfrastructure();
builder.Services.AddRedisInfrastructure(builder.Configuration);
builder.Services.ConfigureCloudinaryOptionsInfrastucture(builder.Configuration.GetSection(nameof(CloudinaryOptions)));
builder.Services.ConfigureMailOptionsInfrastucture(builder.Configuration.GetSection(nameof(MailOption)));

// Add Middleware => Remember using middleware
builder.Services.AddTransient<ExceptionHandlingMiddleware>();
18 changes: 12 additions & 6 deletions MBS-COMMAND.API/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
{
"ConnectionStrings": {
// "ConnectionStrings": "Server=103.162.14.116;Database=PRN_SUPER;Uid=sa;Pwd=MyStrongPassword123@;Trust Server Certificate=True;",
"ConnectionStrings": "Server=(local);Database=PRN_SUPER;Uid=sa;Pwd=12345;Trust Server Certificate=True;",
"ConnectionStrings": "Server=103.162.14.116;Database=PRN_SUPER;Uid=sa;Pwd=MyStrongPassword123@;Trust Server Certificate=True;",
"Redis": "103.162.14.116:6379,password=MyStrongPassword123@,abortConnect=false"
},
"JwtOption": {
@@ -11,17 +10,24 @@
"ExpireMin": 5
},
"MasstransitConfiguration": {
"Host": "localhost",
"VHost": "phucnghi",
"Host": "103.162.14.116",
"VHost": "myHost",
"Port": 5672,
"UserName": "guest",
"Password": "guest"
"UserName": "sa",
"Password": "MyStrongPassword123@"
},
"MessageBusOptions": {
"retryLimit": 3,
"initialInterval": "00:00:05",
"intervalIncrement": "00:00:10"
},
"MailOption": {
"Mail": "contact.antreevn@gmail.com",
"DisplayName": "Antree",
"Password": "aymfdegtavaixpyo",
"Host": "smtp.gmail.com",
"Port": 587
},
"CloudinaryOptions" : {
"CloudName": "dejf8mmou",
"ApiKey": "352838987568689",
7 changes: 7 additions & 0 deletions MBS-COMMAND.API/appsettings.json
Original file line number Diff line number Diff line change
@@ -26,6 +26,13 @@
"ApiKey": "352838987568689",
"ApiSecret": "a3GLia6ovHgc-8xit46QEs8usWY"
},
"MailOption": {
"Mail": "contact.antreevn@gmail.com",
"DisplayName": "Antree",
"Password": "aymfdegtavaixpyo",
"Host": "smtp.gmail.com",
"Port": 587
},
"SqlServerRetryOptions": {
"MaxRetryCount": 5,
"MaxRetryDelay": "00:00:05",
14 changes: 14 additions & 0 deletions MBS_COMMAND.Application/Abstractions/IMailService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace MBS_COMMAND.Application.Abstractions;

public interface IMailService
{
Task SendMail(MailContent mailContent);
}

public class MailContent
{
public string? To { get; set; } // Địa chỉ gửi đến
public string? Subject { get; set; } // Chủ đề (tiêu đề email)
public string? Body { get; set; } // Nội dung (hỗ trợ HTML) của email

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using MBS_AUTHORIZATION.Domain.Entities;
using MBS_COMMAND.Application.Abstractions;
using MBS_COMMAND.Contract.Abstractions.Messages;
using MBS_COMMAND.Contract.Abstractions.Shared;
2 changes: 0 additions & 2 deletions MBS_COMMAND.Domain/Entities/MentorSkills.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using MBS_AUTHORIZATION.Domain.Entities;
using MBS_COMMAND.Contract.Services.MentorSkills;
using MBS_COMMAND.Domain.Abstractions.Aggregates;
using MBS_COMMAND.Domain.Abstractions.Entities;
using DomainEventShared = MBS_CONTRACT.SHARE.Services.Mentors.DomainEvent;
Original file line number Diff line number Diff line change
@@ -9,6 +9,7 @@
using Newtonsoft.Json;
using Quartz;
using MBS_COMMAND.Infrastucture.Caching;
using MBS_COMMAND.Infrastucture.Mail;
using MBS_COMMAND.Infrastucture.DependencyInjection.Options;
using MBS_COMMAND.Infrastucture.PipeObservers;
using MBS_COMMAND.Infrastucture.Media;
@@ -19,8 +20,10 @@ namespace MBS_COMMAND.Infrastucture.DependencyInjection.Extensions;
public static class ServiceCollectionExtensions
{
public static void AddServicesInfrastructure(this IServiceCollection services)
=> services.AddTransient<ICacheService, CacheService>()
.AddTransient<IMediaService, CloudinaryService>()
=> services
.AddTransient<ICacheService, CacheService>()
.AddSingleton<IMediaService, CloudinaryService>()
.AddSingleton<IMailService, MailService>()
.AddSingleton<Cloudinary>((provider) =>
{
var options = provider.GetRequiredService<IOptionsMonitor<CloudinaryOptions>>();
@@ -137,6 +140,13 @@ public static OptionsBuilder<CloudinaryOptions> ConfigureCloudinaryOptionsInfras
.ValidateDataAnnotations()
.ValidateOnStart();

public static OptionsBuilder<MailOption> ConfigureMailOptionsInfrastucture(this IServiceCollection services, IConfigurationSection section)
=> services
.AddOptions<MailOption>()
.Bind(section)
.ValidateDataAnnotations()
.ValidateOnStart();

// Configure MediatR
public static void AddMediatRInfrastructure(this IServiceCollection services)
{
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;

namespace MBS_COMMAND.Infrastucture.DependencyInjection.Options;

public class MailOption
{

[Required]public string Mail { get; set; }
[Required]public string DisplayName { get; set; }
[Required]public string Password { get; set; }
[Required]public string Host { get; set; }
[Required]public int Port { get; set; }
}
1 change: 1 addition & 0 deletions MBS_COMMAND.Infrastucture/MBS_COMMAND.Infrastucture.csproj
Original file line number Diff line number Diff line change
@@ -16,6 +16,7 @@

<ItemGroup>
<PackageReference Include="CloudinaryDotNet" Version="1.26.2" />
<PackageReference Include="MailKit" Version="4.8.0" />
<PackageReference Include="MassTransit" Version="8.2.5" />
<PackageReference Include="MassTransit.Newtonsoft" Version="8.2.5" />
<PackageReference Include="MassTransit.RabbitMQ" Version="8.2.5" />
59 changes: 59 additions & 0 deletions MBS_COMMAND.Infrastucture/Mail/MailService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using MailKit.Security;
using MBS_COMMAND.Application.Abstractions;
using MBS_COMMAND.Infrastucture.DependencyInjection.Options;
using Microsoft.Extensions.Options;
using MimeKit;

namespace MBS_COMMAND.Infrastucture.Mail;

public class MailService : IMailService
{
private readonly MailOption _mailOptions;

public MailService(IOptions<MailOption> mailOptions)
{
_mailOptions = mailOptions.Value;
}

public async Task SendMail(MailContent mailContent)
{
MimeMessage email = new();
email.Sender = new MailboxAddress(_mailOptions?.DisplayName, _mailOptions?.Mail);
email.From.Add(new MailboxAddress(_mailOptions?.DisplayName, _mailOptions?.Mail));
email.To.Add(MailboxAddress.Parse(mailContent.To));
email.Subject = mailContent.Subject;


BodyBuilder builder = new();
builder.HtmlBody = mailContent.Body;
email.Body = builder.ToMessageBody();

// dùng SmtpClient của MailKit
using MailKit.Net.Smtp.SmtpClient smtp = new();

await smtp.ConnectAsync(_mailOptions?.Host, _mailOptions!.Port, SecureSocketOptions.StartTls);
await smtp.AuthenticateAsync(_mailOptions.Mail, _mailOptions.Password);
await smtp.SendAsync(email);

// try
// {
// smtp.Connect(_mailOptions?.Host, _mailOptions!.Port, SecureSocketOptions.StartTls);
// smtp.Authenticate(_mailOptions.Mail, _mailOptions.Password);
// await smtp.SendAsync(email);
// }
// catch (Exception ex)
// {
// // Gửi mail thất bại, nội dung email sẽ lưu vào thư mục mailssave
// // System.IO.Directory.CreateDirectory("mailssave");
// // var emailsavefile = string.Format(@"mailssave/{0}.eml", Guid.NewGuid());
// // await email.WriteToAsync(emailsavefile);
//
// System.Console.WriteLine("errors: ", ex);
//
// // logger.LogInformation("Lỗi gửi mail, lưu tại - " + emailsavefile);
// // logger.LogError(ex.Message);
// }

await smtp.DisconnectAsync(true);
}
}

0 comments on commit 6dad47f

Please sign in to comment.