Email.cshtml.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using Application.Features.Config;
  2. using Application.Features.Config.Commands;
  3. using Application.Features.Config.Queries;
  4. using Application.Abstractions.Messaging.Email;
  5. using MediatR;
  6. using Microsoft.AspNetCore.Mvc;
  7. using Microsoft.AspNetCore.Mvc.RazorPages;
  8. using Microsoft.Extensions.Options;
  9. using SharedKernel;
  10. using System.ComponentModel;
  11. using System.ComponentModel.DataAnnotations;
  12. namespace Admin.Pages.Config.Test
  13. {
  14. public class EmailModel(IMediator mediator, IOptions<AppSettings> options, IMailService mailService) : PageModel
  15. {
  16. public readonly AppSettings Settings = options.Value;
  17. [BindProperty]
  18. [MaxLength(256)]
  19. [DataType(DataType.EmailAddress)]
  20. [DisplayName("To Address")]
  21. public string? ToAddress { get; set; }
  22. [BindProperty]
  23. public InputModel Input { get; set; } = new();
  24. public async Task OnGetAsync(CancellationToken cancellationToken)
  25. {
  26. var config = await mediator.Send(new GetConfigQuery(), cancellationToken);
  27. if (config is not null)
  28. {
  29. Input = InputModel.From(config);
  30. }
  31. }
  32. public async Task<IActionResult> OnPostAsync(CancellationToken cancellationToken)
  33. {
  34. if (!ModelState.IsValid)
  35. {
  36. return Page();
  37. }
  38. await mailService.SendAsync(
  39. new SendData(
  40. ToAddress: ToAddress!,
  41. Subject: $"[TEST] SMTP 이메일 발송 테스트 - {DateTime.Now:yyyy-MM-dd HH:mm:ss}",
  42. MessageHtml: $"""
  43. <h3>테스트 메일</h3>
  44. <ul>
  45. <li>From: {Settings.SMTP.FromName} &lt;{Settings.SMTP.FromEmail}&gt;</li>
  46. <li>To: {ToAddress}</li>
  47. <li>Host: {Settings.SMTP.Host}:{Settings.SMTP.Port}</li>
  48. <li>TLS: {Settings.SMTP.UseStartTls}</li>
  49. </ul>
  50. """,
  51. MessageText: $"TEST MAIL\nFrom={Settings.SMTP.FromEmail}\nTo={ToAddress}\nHost={Settings.SMTP.Host}:{Settings.SMTP.Port}\nTLS={Settings.SMTP.UseStartTls}"
  52. ),
  53. cancellationToken
  54. );
  55. TempData["SuccessMessage"] = "테스트 이메일을 발송했습니다.";
  56. return RedirectToPage();
  57. }
  58. public sealed class InputModel
  59. {
  60. public ConfigDto.BasicConfigDto Basic { get; set; } = new();
  61. public static InputModel From(ConfigDto config)
  62. {
  63. return new()
  64. {
  65. Basic = config.Basic
  66. };
  67. }
  68. public UpdateConfigCommand ToCommand()
  69. {
  70. return new(
  71. Basic
  72. );
  73. }
  74. }
  75. }
  76. }