diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..3729ff0 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,25 @@ +**/.classpath +**/.dockerignore +**/.env +**/.git +**/.gitignore +**/.project +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/*.*proj.user +**/*.dbmdl +**/*.jfm +**/azds.yaml +**/bin +**/charts +**/docker-compose* +**/Dockerfile* +**/node_modules +**/npm-debug.log +**/obj +**/secrets.dev.yaml +**/values.dev.yaml +LICENSE +README.md \ No newline at end of file diff --git a/Controllers/EmailController.cs b/Controllers/EmailController.cs new file mode 100644 index 0000000..b5bade8 --- /dev/null +++ b/Controllers/EmailController.cs @@ -0,0 +1,129 @@ +using Microsoft.AspNetCore.Mvc; +using EmailServiceApi.Services; + +using EmailServiceApi.Models; + +namespace EmailServiceApi.Controllers +{ + [ApiController] + [Route("[controller]")] + + public class EmailController : ControllerBase + { + private readonly EmailService _emailService; + /// + /// Email Testing API + /// + /// + public EmailController(EmailService emailService) + { + _emailService = emailService; + } + /// + /// Generate Sample Request for Method I (provide user name and password) + /// + /// + [HttpGet("methode1/request")] + public ActionResult GetMailParameters4Method1() + { + try + { + var emailRequest = new EmailRequest1 + { + smptserver = "mail-00.dadeschools.net", + Subject = "Test WB", + FromAddress = "no-reply@dadeschools.net", + ToAddress = "", + Message = "Testemail", + username = "username", + password = "password", + // Times = 1 + + }; + + return Ok(emailRequest); + } + catch (Exception ex) + { + return StatusCode(500, "An error occurred while processing the request."); + } + } + /// + ///Send email using methode I + /// + /// + /// + [HttpPost("methode1/send")] + public ActionResult SendMethode1([FromBody] EmailRequest1 request) + { + try + { + _emailService.SendEmailmethode1(request.smptserver = "mail-00.dadeschools.net", request.FromAddress, request.ToAddress, request.Subject, request.Message, request.username, request.password); + return Ok("Email sent successfully."); + } + catch (Exception ex) + { + return StatusCode(500, $"Failed to send email: {ex.Message}"); + } + } + + /// + /// Generate Sample Request for Method II + /// + /// + [HttpGet("methode2/request")] + public ActionResult GetMailParameters4Method2() + { + try + { + var emailRequest = new EmailRequest2 + { + smptserver= "mail-00.dadeschools.net", + Subject = "Test WB", + FromAddress = "no-reply@dadeschools.net", + ToAddress = "", + Message="Testemail", + Times=1 + + }; + + return Ok(emailRequest); + } + catch (Exception ex) + { + return StatusCode(500, "An error occurred while processing the request."); + } + } + + + /// + /// Send email using methode II + /// + /// + /// + [HttpPost("methode2/send")] + public ActionResult SendMthode2([FromBody] EmailRequest2 request) + { + try + { + _emailService.SendEmailMethode2(request.smptserver, request.FromAddress, request.ToAddress, request.Subject, request.Message, request.Times); + return Ok("Email sent successfully."); + } + catch (Exception ex) + { + return StatusCode(500, $"Failed to send email: {ex.Message}"); + } + } + + + } + + //public class EmailRequest + //{ + // public string SmtpServer { get; set; } + // public string FromAddress { get; set; } + // public string ToAddress { get; set; } + // public string Subject { get; set; } + // public string Body { get; set; } + //} +} diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..0ac10b5 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,22 @@ +#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging. + +FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base +WORKDIR /app +EXPOSE 80 +EXPOSE 443 + +FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build +WORKDIR /src +COPY ["EmailServiceApi.csproj", "."] +RUN dotnet restore "./EmailServiceApi.csproj" +COPY . . +WORKDIR "/src/." +RUN dotnet build "EmailServiceApi.csproj" -c Release -o /app/build + +FROM build AS publish +RUN dotnet publish "EmailServiceApi.csproj" -c Release -o /app/publish /p:UseAppHost=false + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "EmailServiceApi.dll"] \ No newline at end of file diff --git a/EmailServiceApi.csproj b/EmailServiceApi.csproj new file mode 100644 index 0000000..76c4ab4 --- /dev/null +++ b/EmailServiceApi.csproj @@ -0,0 +1,21 @@ + + + + net6.0 + enable + enable + da285c03-9c5c-4529-bc6a-0dab7897770e + Linux + . + True + + + + + + + + + + + diff --git a/EmailServiceApi.sln b/EmailServiceApi.sln new file mode 100644 index 0000000..626ff32 --- /dev/null +++ b/EmailServiceApi.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.7.34031.279 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EmailServiceApi", "EmailServiceApi.csproj", "{A4017F77-8FC9-4816-AF54-90B55F66BDE1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A4017F77-8FC9-4816-AF54-90B55F66BDE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A4017F77-8FC9-4816-AF54-90B55F66BDE1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A4017F77-8FC9-4816-AF54-90B55F66BDE1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A4017F77-8FC9-4816-AF54-90B55F66BDE1}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {7DF01419-602A-4A78-A48E-FC29388D5914} + EndGlobalSection +EndGlobal diff --git a/Models/EmailRequest.cs b/Models/EmailRequest.cs new file mode 100644 index 0000000..c917659 --- /dev/null +++ b/Models/EmailRequest.cs @@ -0,0 +1,24 @@ +namespace EmailServiceApi.Models +{ + public class EmailRequest2 + { + public string smptserver { get; set; } + public string? FromAddress { get; set; } + public string ToAddress { get; set; } + public string? Subject { get; set; } + public string? Message { get; set; } + public int? Times { get; set; } = 1; + } + public class EmailRequest1 + { + public string smptserver { get; set; } + public string? FromAddress { get; set; } + public string ToAddress { get; set; } + public string? Subject { get; set; } + public string? Message { get; set; } + public string username { get; set; } + public string password { get; set; } + } + + +} diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..9fe88a8 --- /dev/null +++ b/Program.cs @@ -0,0 +1,38 @@ + + +using EmailServiceApi.Services; +using System.Reflection; + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. + +builder.Services.AddControllers(); +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); +builder.Services.AddSwaggerGen(c => +{ + // Include XML comments from your assembly + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); +}); + +builder.Services.AddScoped(); +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); + +app.UseAuthorization(); + +app.MapControllers(); + +app.Run(); diff --git a/Properties/launchSettings.json b/Properties/launchSettings.json new file mode 100644 index 0000000..b028f8d --- /dev/null +++ b/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "profiles": { + "EmailServiceApi": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "dotnetRunMessages": true, + "applicationUrl": "https://localhost:7192;http://localhost:5191" + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "Docker": { + "commandName": "Docker", + "launchBrowser": true, + "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger", + "environmentVariables": { + "ASPNETCORE_URLS": "https://+:443;http://+:80" + }, + "publishAllPorts": true, + "useSSL": true + } + }, + "$schema": "https://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:50519", + "sslPort": 44333 + } + } +} \ No newline at end of file diff --git a/Services/EmailService.cs b/Services/EmailService.cs new file mode 100644 index 0000000..5b69729 --- /dev/null +++ b/Services/EmailService.cs @@ -0,0 +1,93 @@ +using MimeKit; +using System; +using MailKit.Net.Smtp; +using MailKit.Security; +using MailKit; +using MailKit.Security; + +using System.Net.Mail; + +namespace EmailServiceApi.Services +{ + public class EmailService + { + + + public string SendEmailmethode1(string smtpServer, string fromAddress, string toAddress, string subject, string body,string username,string password) + { + try + { + // Create MimeMessage + var message = new MimeMessage(); + message.From.Add(new MailboxAddress("Sender Name", fromAddress)); + message.To.Add(new MailboxAddress("Recipient Name", toAddress)); + message.Subject = subject; + + // Create body part + var bodyPart = new TextPart("plain") + { + Text = body + }; + + // Construct the multipart/mixed container to hold the message text and any attachments + var multipart = new Multipart("mixed"); + multipart.Add(bodyPart); + + // Add the multipart/alternative part to the message + message.Body = multipart; + + // Send email using MailKit + using (var client = new MailKit.Net.Smtp.SmtpClient()) + { + client.Connect(smtpServer, 587, SecureSocketOptions.StartTls); // Assuming SMTP server is using port 587 for TLS encryption + client.Authenticate(username, password); // Provide credentials here if required by your SMTP server + client.Send(message); + client.Disconnect(true); + } + + return "Email sent successfully."; + } + catch (Exception ex) + { + string errorMessage = "Failed to send email(methode 1): " + ex.Message; + + // Check if inner exception exists and its message is not null + if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message)) + { + errorMessage += "\n Details: " + ex.InnerException.Message; + } + + throw new Exception(errorMessage); + } + } + public string SendEmailMethode2(string smtpServer, string fromAddress, string toAddress, string subject, string body, int? times = 1) + { + try + { + MailMessage oEmail = new MailMessage(fromAddress, toAddress, subject, body); + var emailClient2 = new System.Net.Mail.SmtpClient(smtpServer); + + for (int i = 0; i < times; i++) + { + oEmail.Subject = subject + " (" + i + ")"; + emailClient2.Send(oEmail); //Send email + } + + return "Email sent successfully."; + } + catch (Exception ex) + { + string errorMessage = "Failed to send email(methode 2): " + ex.Message; + + // Check if inner exception exists and its message is not null + if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message)) + { + errorMessage += "\n Details: " + ex.InnerException.Message; + } + + throw new Exception(errorMessage); + // return $"Failed to send email: {ex.Message}"; + } + } + } +} diff --git a/appsettings.Development.json b/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/appsettings.json b/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +}