Send Email
In this article, you will see how to send email from ASP.NET Core Website using MailKit.
Install the Required Packages
Install-Package MailKit
Install-Package MimeKit
Send Email using MailKit
Basic code for sending email.
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse("[from-email]"));
email.To.Add(MailboxAddress.Parse("[to-email]"));
email.Subject = "[subject]";
var builder = new BodyBuilder();
builder.HtmlBody = "[body]";
email.Body = builder.ToMessageBody();
using var smtp = new SmtpClient(new ProtocolLogger("smtp.log"));
smtp.ServerCertificateValidationCallback = (s, c, h, e) => true;
smtp.Connect("[host]", "[port]", SecureSocketOptions.Auto);
smtp.Authenticate("[username]", "[password]");
await smtp.SendAsync(email);
smtp.Disconnect(true);
Replace the content in the square brackets with actual value.
Attachments
attachments is of type List<IFormFile>
byte[] fileBytes;
foreach (var file in attachments)
{
if (file.Length > 0)
{
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
fileBytes = ms.ToArray();
}
builder.Attachments.Add(file.FileName, fileBytes, ContentType.Parse(file.ContentType));
}
}
Fake Email Provider
Ethereal - a fake SMTP service.