using MailKit.Net.Smtp;
using MimeKit;
using Microsoft.AspNetCore.Mvc;
namespace EmailSenderApp.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EmailController : ControllerBase
{
// Load environment variables (or use default values)
private readonly string smtpHost = Environment.GetEnvironmentVariable("MAIL_HOST") ?? "smtp.c1.liara.email";
private readonly int smtpPort = int.Parse(Environment.GetEnvironmentVariable("MAIL_PORT") ?? "465");
private readonly string smtpUser = Environment.GetEnvironmentVariable("MAIL_USER") ?? "";
private readonly string smtpPassword = Environment.GetEnvironmentVariable("MAIL_PASSWORD") ?? "";
private readonly string mailFromAddress = Environment.GetEnvironmentVariable("MAIL_FROM_ADDRESS") ?? "";
[HttpGet("send-test-email")]
public async Task<IActionResult> SendTestEmail()
{
var recipientEmail = "[email protected]"; // Replace with recipient email
// Create the email
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse(mailFromAddress));
email.To.Add(MailboxAddress.Parse(recipientEmail));
email.Subject = "Test Email";
email.Body = new TextPart("plain")
{
Text = "This is a test email sent using explicit TLS without STARTTLS."
};
// Add custom header
email.Headers.Add("x-liara-tag", "test-tag");
try
{
// Send the email
using var client = new SmtpClient();
await client.ConnectAsync(smtpHost, smtpPort, MailKit.Security.SecureSocketOptions.SslOnConnect);
await client.AuthenticateAsync(smtpUser, smtpPassword);
await client.SendAsync(email);
await client.DisconnectAsync(true);
// Return success response
return Ok("Email sent successfully with custom header!");
}
catch (Exception ex)
{
// Handle errors and return error response
return StatusCode(500, $"Failed to send email: {ex.Message}");
}
}
}
}