case 4670 whups nearly missed an addition of services all ready to merge now for real
This commit is contained in:
47
Services/MailSender.cs
Normal file
47
Services/MailSender.cs
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
using System.Threading.Tasks;
|
||||||
|
using MailKit.Net.Smtp;
|
||||||
|
using MailKit.Security;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using MimeKit;
|
||||||
|
|
||||||
|
namespace contact.Services
|
||||||
|
{
|
||||||
|
//Sends web form submissions to support.
|
||||||
|
//From is always the authenticated account; the visitor goes in Reply-To, so there is no sender spoofing.
|
||||||
|
//SMTP settings come from the "Smtp" config section; the password is never in source.
|
||||||
|
public class MailSender
|
||||||
|
{
|
||||||
|
private const string SupportAddress = "support@ayanova.com";
|
||||||
|
private readonly IConfiguration _configuration;
|
||||||
|
|
||||||
|
public MailSender(IConfiguration configuration)
|
||||||
|
{
|
||||||
|
_configuration = configuration;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task SendToSupportAsync(string subject, string body, string visitorName, string visitorEmail)
|
||||||
|
{
|
||||||
|
var smtp = _configuration.GetSection("Smtp");
|
||||||
|
|
||||||
|
var message = new MimeMessage();
|
||||||
|
message.From.Add(new MailboxAddress("AyaNova web forms", smtp["User"]));
|
||||||
|
message.To.Add(MailboxAddress.Parse(SupportAddress));
|
||||||
|
if (MailboxAddress.TryParse(visitorEmail, out var replyTo))
|
||||||
|
{
|
||||||
|
replyTo.Name = visitorName;
|
||||||
|
message.ReplyTo.Add(replyTo);
|
||||||
|
}
|
||||||
|
message.Subject = OneLine(subject);
|
||||||
|
message.Body = new TextPart("plain") { Text = body };
|
||||||
|
|
||||||
|
using var client = new SmtpClient();
|
||||||
|
await client.ConnectAsync(smtp["Host"], smtp.GetValue<int>("Port"), SecureSocketOptions.StartTls);
|
||||||
|
await client.AuthenticateAsync(smtp["User"], smtp["Password"]);
|
||||||
|
await client.SendAsync(message);
|
||||||
|
await client.DisconnectAsync(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
//Subjects include visitor-supplied text; a hand-crafted POST could put line breaks in it
|
||||||
|
private static string OneLine(string s) => s.Replace("\r", " ").Replace("\n", " ");
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user