Skip to content

Commit 3d9da3f

Browse files
authored
Add files via upload
1 parent 9cfa92f commit 3d9da3f

21 files changed

+623
-0
lines changed
+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+

2+
using Microsoft.Extensions.Options;
3+
4+
namespace SimpleEmailApp.ConfgureSetting
5+
{
6+
public interface IWritableOptionsMail<out T> : IOptionsSnapshot<T> where T : class, new()
7+
{
8+
void Update(Action<T> applyChanges);
9+
}
10+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
using Microsoft.Extensions.Options;
2+
3+
namespace SimpleEmailApp.ConfgureSetting
4+
{
5+
public static class ServiceCollectionExtensions
6+
{
7+
public static void ConfigureWritable<T>(
8+
this IServiceCollection services,
9+
IConfigurationSection section,
10+
string file = "appsettings.json") where T : class, new()
11+
{
12+
services.Configure<T>(section);
13+
services.AddTransient<IWritableOptionsMail<T>>(provider =>
14+
{
15+
var configuration = (IConfigurationRoot)provider.GetService<IConfiguration>();
16+
var environment = provider.GetService<IWebHostEnvironment>();
17+
var options = provider.GetService<IOptionsSnapshot<T>>();
18+
19+
return new WritableOptionsMail<T>(environment, options, configuration, section.Key, file);
20+
});
21+
}
22+
}
23+
}
+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
using Microsoft.AspNetCore.Hosting;
2+
using Microsoft.Extensions.Configuration;
3+
using Microsoft.Extensions.Options;
4+
using System.Text.Json;
5+
using System.Text.Json.Nodes;
6+
7+
8+
namespace SimpleEmailApp.ConfgureSetting
9+
{
10+
public class WritableOptionsMail<T> : IWritableOptionsMail<T> where T : class, new()
11+
{
12+
//private properties
13+
private readonly IWebHostEnvironment _environment;
14+
private readonly IOptionsSnapshot<T> _options;
15+
private readonly IConfigurationRoot _configuration;
16+
private readonly string _section;
17+
private readonly string _file;
18+
//costructor
19+
public WritableOptionsMail(IWebHostEnvironment environment, IOptionsSnapshot<T> options, IConfigurationRoot configuration, string section, string file)
20+
{
21+
_environment = environment;
22+
_options = options;
23+
_configuration = configuration;
24+
_section = section;
25+
_file = file;
26+
}
27+
//T value for generics type
28+
public T Value => _options.Value;
29+
public T Get(string name) => _options.Get(name);
30+
31+
public void Update(Action<T> applyChanges)
32+
{
33+
var fileProvider = _environment.ContentRootFileProvider;
34+
var fileInfo = fileProvider.GetFileInfo(_file);
35+
var physicalPath = fileInfo.PhysicalPath;
36+
var jObject = JsonSerializer.Deserialize<JsonObject>(File.ReadAllText(physicalPath)); //<JObject>(File.ReadAllText(physicalPath));
37+
38+
if (jObject is null)
39+
return;
40+
41+
var sectionObject = jObject.TryGetPropertyValue(_section, out JsonNode? section) ?
42+
JsonSerializer.Deserialize<T>(section?.ToString()) : (Value ?? new T());
43+
44+
applyChanges(sectionObject);
45+
jObject[_section] = JsonObject.Parse(JsonSerializer.Serialize(sectionObject));
46+
File.WriteAllText(physicalPath, JsonSerializer.Serialize(jObject, new JsonSerializerOptions { WriteIndented = true }));
47+
_configuration.Reload();
48+
}
49+
}
50+
}

Controllers/MailController.cs

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+

2+
using Microsoft.AspNetCore.Mvc;
3+
using SimpleEmailApp.CorrelationService;
4+
using System.Text.Json;
5+
6+
namespace SimpleEmailApp.Controllers
7+
{
8+
[Route("api/[controller]")]
9+
[ApiController]
10+
public class MailController : ControllerBase
11+
{
12+
private readonly IMailService _mailService;
13+
private readonly ILogger<MailController> _logger;
14+
private readonly ICorrelationIdGenerator _correlationIdGenerator;
15+
public MailController(IMailService mailService, ILogger<MailController> logger,
16+
ICorrelationIdGenerator correlationIdGenerator)
17+
{
18+
_mailService = mailService;
19+
_logger = logger;
20+
_correlationIdGenerator = correlationIdGenerator;
21+
}
22+
23+
[HttpPost]
24+
public async Task<IActionResult> SendMail([FromForm] EmailMessage req)
25+
{
26+
_logger.LogInformation("..................... Sending Email Function Start.............");
27+
try
28+
{
29+
await _mailService.SendEmailAsync(req);
30+
_logger.LogInformation("CorrelationId {correlationId}: ",
31+
_correlationIdGenerator.Get());
32+
33+
//_logger.LogInformation($" Email {},{req.Reciver},{req.Subject},{req.Body} is send.");
34+
return Ok($"Email sended to {req.Reciver} sucessfully.");
35+
36+
}
37+
catch (Exception)
38+
{
39+
return NotFound();
40+
// _logger.LogError("We have error in sending Email.");
41+
}
42+
43+
44+
}
45+
46+
47+
48+
//public IActionResult SendEmail(string subject , string body , string sender)
49+
//{
50+
// var email = new MimeMessage();
51+
// email.From.Add(MailboxAddress.Parse("anivargudeov@gmail.com"));
52+
// email.To.Add(MailboxAddress.Parse("anivargudeov@gmail.com"));
53+
// email.Subject = subject;
54+
// email.Body =new TextPart(TextFormat.Plain) { Text= body };
55+
56+
// using var smtp = new SmtpClient();
57+
// smtp.Connect("smtp.gmail.com", 587,SecureSocketOptions.StartTls);
58+
// smtp.Authenticate("anivargudeov@gmail.com", "fsobaslupqqlmhtv");
59+
// smtp.Send(email);
60+
// smtp.Disconnect(true);
61+
// return Ok();
62+
//}
63+
64+
}
65+
}
+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
using Microsoft.AspNetCore.Http;
2+
using Microsoft.AspNetCore.Mvc;
3+
using SimpleEmailApp.ConfgureSetting;
4+
5+
namespace SimpleEmailApp.Controllers
6+
{
7+
[Route("api/[controller]")]
8+
[ApiController]
9+
public class SMTPConfigurationController : ControllerBase
10+
{
11+
12+
private readonly IWritableOptionsMail<AppSetting> _writableMail;
13+
private readonly ILogger<SMTPConfigurationController> _logger;
14+
//IWritableOptionsMail<AppSetting> writableMail
15+
public SMTPConfigurationController(IWritableOptionsMail<AppSetting> writableMail,
16+
ILogger<SMTPConfigurationController> logger)
17+
{
18+
_writableMail = writableMail;
19+
_logger = logger;
20+
}
21+
22+
23+
[HttpPost]
24+
public IActionResult ConfigureSettings(string SenderMail, string password, string host, int port)
25+
{
26+
var setting = new AppSetting()
27+
{
28+
Mail = SenderMail,
29+
Password = password,
30+
Host = host,
31+
Port = port
32+
};
33+
34+
35+
if (setting == null)
36+
{
37+
return BadRequest("you should Enter configuration for SMTP Server");
38+
}
39+
try
40+
{
41+
_writableMail.Update(opt =>
42+
{
43+
opt.Mail = setting.Mail;
44+
opt.Password = setting.Password;
45+
opt.Host = setting.Host;
46+
opt.Port = setting.Port;
47+
});
48+
_logger.LogInformation("New SMTP Configuration {setting} is created. ",setting);
49+
}
50+
catch(Exception)
51+
{
52+
_logger.LogError("SMTP configuration has error.");
53+
throw;
54+
}
55+
56+
57+
// if (_settings != null)
58+
return Ok("configuration is added into setting .");
59+
}
60+
61+
}
62+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
namespace SimpleEmailApp.CorrelationService
2+
{
3+
public class CorrelationIdGenerator : ICorrelationIdGenerator
4+
{
5+
private string _correlationId = Guid.NewGuid().ToString();
6+
7+
public string Get() => _correlationId;
8+
9+
public void Set(string correlationId)
10+
{
11+
_correlationId = correlationId;
12+
}
13+
}
14+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
namespace SimpleEmailApp.CorrelationService
2+
{
3+
public interface ICorrelationIdGenerator
4+
{
5+
string Get();
6+
void Set(string correlationId);
7+
}
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
using Microsoft.Extensions.Primitives;
2+
using SimpleEmailApp.CorrelationService;
3+
4+
namespace SimpleEmailApp.CorrelationService.Middleware
5+
{
6+
public class CorrelationIdMiddleware
7+
{
8+
private readonly RequestDelegate _next;
9+
private const string _correlationIdHeader = "X-Correlation-Id";
10+
11+
public CorrelationIdMiddleware(RequestDelegate next)
12+
{
13+
_next = next;
14+
}
15+
16+
public async Task Invoke(HttpContext context, ICorrelationIdGenerator correlationIdGenerator)
17+
{
18+
var correlationId = GetCorrelationId(context, correlationIdGenerator);
19+
AddCorrelationIdHeaderToResponse(context, correlationId);
20+
21+
await _next(context);
22+
}
23+
24+
private static StringValues GetCorrelationId(HttpContext context, ICorrelationIdGenerator correlationIdGenerator)
25+
{
26+
if (context.Request.Headers.TryGetValue(_correlationIdHeader, out var correlationId))
27+
{
28+
correlationIdGenerator.Set(correlationId);
29+
return correlationId;
30+
}
31+
else
32+
{
33+
return correlationIdGenerator.Get();
34+
}
35+
}
36+
37+
private static void AddCorrelationIdHeaderToResponse(HttpContext context, StringValues correlationId)
38+
{
39+
context.Response.OnStarting(() =>
40+
{
41+
context.Response.Headers.Add(_correlationIdHeader, new[] { correlationId.ToString() });
42+
return Task.CompletedTask;
43+
});
44+
}
45+
}
46+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
using SimpleEmailApp.CorrelationService.Middleware;
2+
3+
namespace SimpleEmailApp.CorrelationService.Service
4+
{
5+
public static class ApplicationBuilderExtensions
6+
{
7+
public static IApplicationBuilder AddCorrelationIdMiddleware(this IApplicationBuilder applicationBuilder)
8+
=> applicationBuilder.UseMiddleware<CorrelationIdMiddleware>();
9+
}
10+
}

Model/AppSetting.cs

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
using System.Text.Json;
2+
namespace SimpleEmailApp.Model
3+
{
4+
5+
public class AppSetting
6+
{
7+
public string Mail { get; set; } = string.Empty;
8+
// public string DisplayName { get; set; } = string.Empty;
9+
public string Password { get; set; } = string.Empty;
10+
public string Host { get; set; } = string.Empty;
11+
public int Port { get; set; }
12+
}
13+
}

Model/EmailMessage.cs

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+

2+
using Serilog;
3+
namespace SimpleEmailApp.Model
4+
{
5+
public class EmailMessage
6+
{
7+
public string Reciver { get; set; } = string.Empty;
8+
// public string Sender { get; set; } = string.Empty;
9+
public string Subject { get; set; } = string.Empty;
10+
public string Body { get; set; } = string.Empty;
11+
// public List<IFormFile> Attachments { get; set; }
12+
}
13+
}

Model/EmailMessageLog.cs

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
namespace SimpleEmailApp.Model
2+
{
3+
public class EmailMessageLog
4+
{
5+
public int Id { get; set; }
6+
public string Reciver { get; set; } = string.Empty;
7+
public string Sender { get; set; } = string.Empty;
8+
public string Subject { get; set; } = string.Empty;
9+
public string Body { get; set; }
10+
11+
public EmailMessageLog(int id,string recive,string send,string subject, string body)
12+
{
13+
Id = id;
14+
Reciver = recive;
15+
Sender = send;
16+
Subject = subject;
17+
Body = body;
18+
}
19+
}
20+
}

0 commit comments

Comments
 (0)