TestController.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System.Diagnostics;
  2. using bitforum.Models;
  3. using bitforum.Repository;
  4. using Microsoft.AspNetCore.Authorization;
  5. using Microsoft.AspNetCore.Mvc;
  6. using bitforum.Helpers;
  7. using System.Net.Mail;
  8. using System.Net;
  9. namespace bitforum.Controllers.Setting
  10. {
  11. [Authorize]
  12. [Route("Setting")]
  13. public class TestController : Controller
  14. {
  15. private readonly ILogger<TestController> _logger;
  16. private readonly ConfigRepository _configRepository;
  17. private readonly string _ViewPath = "~/Views/Setting/Test.cshtml";
  18. public TestController(ILogger<TestController> logger, ConfigRepository configRepository)
  19. {
  20. _logger = logger;
  21. _configRepository = configRepository;
  22. }
  23. [HttpGet("Test")]
  24. public IActionResult Index()
  25. {
  26. ViewBag.config = _configRepository.GetAll();
  27. return View(_ViewPath);
  28. }
  29. [HttpPost("Test")]
  30. public async Task<IActionResult> Send(string? email)
  31. {
  32. try
  33. {
  34. if (string.IsNullOrEmpty(email))
  35. {
  36. TempData["ErrorMessage"] = "이메일 주소를 입력해주세요.";
  37. return RedirectToAction("Test", "Setting");
  38. }
  39. var config = _configRepository.GetAll();
  40. var _smtpServer = config.GetConfig("smtp_server");
  41. var _smtpPort = int.Parse(config.GetConfig("smtp_port"));
  42. var _fromEmail = config.GetConfig("smtp_from_email");
  43. var _emailPassword = config.GetConfig("smtp_email_password");
  44. var client = new SmtpClient(_smtpServer, _smtpPort)
  45. {
  46. Credentials = new NetworkCredential(_fromEmail, _emailPassword),
  47. EnableSsl = true
  48. };
  49. var mailMessage = new MailMessage
  50. {
  51. From = new MailAddress(_fromEmail),
  52. Subject = "Test E-mail",
  53. Body = "현재 이메일을 보고 있거나 받았다면 이메일이 정상적으로 수신된 것입니다.",
  54. IsBodyHtml = false
  55. };
  56. mailMessage.To.Add(email);
  57. await client.SendMailAsync(mailMessage);
  58. TempData["SuccessMessage"] = "이메일이 전송되었습니다.";
  59. return View(_ViewPath);
  60. }
  61. catch (SmtpException smtpEx)
  62. {
  63. Console.WriteLine($"SMTP error: {smtpEx.Message}");
  64. _logger.LogError($"SMTP error: {smtpEx.StatusCode} - {smtpEx.Message}");
  65. throw;
  66. }
  67. catch (Exception ex)
  68. {
  69. Console.WriteLine($"Email sending failed: {ex.Message}");
  70. _logger.LogError($"Failed to send email to {email}: {ex.Message}");
  71. throw;
  72. }
  73. }
  74. [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  75. public IActionResult Error()
  76. {
  77. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  78. }
  79. }
  80. }