Skip to content

Instantly share code, notes, and snippets.

@xivol
Last active April 6, 2026 11:21
Show Gist options
  • Select an option

  • Save xivol/72e09c6130d91a6216c0e8d90970d3e9 to your computer and use it in GitHub Desktop.

Select an option

Save xivol/72e09c6130d91a6216c0e8d90970d3e9 to your computer and use it in GitHub Desktop.
using System.Net;
using System.Net.Mail;
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication2
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<IMailService, MailService>();
var app = builder.Build();
app.MapPost("/api/send-email", async (EmailRequest mailData, IMailService mailService) =>
{
if (mailService.SendEmail(mailData.Email, "Welcome to the Swamp!", "Stay Froggy!"))
{
return Results.Ok("Email sent");
}
else
{
return Results.Problem();
}
});
app.MapGet("/", async context =>
{
context.Response.ContentType = "text/html";
await context.Response.WriteAsync(@"
<!DOCTYPE html>
<html>
<head>
<title>Тест отправки email через Mailgun (SMTP)</title>
<meta charset=""UTF-8"">
</head>
<body>
<h2>Отправка тестового письма через Mailgun (SMTP)</h2>
<form id=""emailForm"">
<input type=""email"" id=""email"" required placeholder=""user@example.com"">
<button type=""submit"">Отправить</button>
</form>
<div id=""result"" class=""result""></div>
<script>
document.getElementById('emailForm').addEventListener('submit', async (e) => {
e.preventDefault();
const resultDiv = document.getElementById('result');
resultDiv.style.display = 'none';
const data = {
email: document.getElementById('email').value
};
try {
const response = await fetch('api/send-email', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const result = await response.json();
resultDiv.className = 'result ' + (response.ok ? 'success' : 'error');
resultDiv.textContent = response.ok ? '✅ ' + result.message : '❌ ' + result.error;
resultDiv.style.display = 'block';
} catch (err) {
resultDiv.className = 'result error';
resultDiv.textContent = '❌ Ошибка сети или сервера: ' + err.message;
resultDiv.style.display = 'block';
}
});
</script>
</body>
</html>
");
});
app.Run();
}
}
public class EmailRequest
{
[Required]
[EmailAddress]
public string Email { get; set; }
}
public interface IMailService
{
bool SendEmail(string toEmail, string subject, string body);
}
public class MailService : IMailService
{
private string _smtpServer = "smtp.mailgun.org";
private int _smtpPort = 587;
private string _smtpUsername = "ваш-smtp-логин";
private string _smtpPassword = "ваш-smtp-пароль";
private string _senderName = "Greenswamp Community";
private string _senderEmail = "info@greenswamp.com";
private readonly ILogger<MailService> _logger;
public MailService(ILogger<MailService> logger)
{
_logger = logger;
}
public bool SendEmail(string toEmail, string subject, string body)
{
try
{
using (var client = new SmtpClient(_smtpServer, _smtpPort))
{
client.EnableSsl = true;
client.Credentials = new NetworkCredential(_smtpUsername, _smtpPassword);
var fromAddress = new MailAddress(_senderEmail, _senderName);
var toAddress = new MailAddress(toEmail);
using (var message = new MailMessage(fromAddress, toAddress))
{
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = true;
client.Send(message);
}
}
_logger.LogInformation("Email successfully sent to {ToEmail}", toEmail);
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "An unexpected error occurred while sending email to {ToEmail}", toEmail);
return false;
}
}
}
}

Comments are disabled for this gist.