Dot Net Core Send Email Using MailKit

MailKit Send Email Using SMTP

using System;
using System.Collections.Generic;
using System.Threading;
using MailKit.Net.Smtp;
using Microsoft.AspNetCore.Mvc;
using MimeKit;

namespace WebAPIApplication.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            ThreadPool.QueueUserWorkItem(async o =>
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("YourName", "YourEmailId"));
                message.To.Add(new MailboxAddress("Mrs. Chanandler Bong", "[email protected]"));
                message.Subject = "How you doin'?";
                // message.Body = new TextPart("plain")
                // {
                //     Text = @"Test Message"
                // };
                var bodyBuilder = new BodyBuilder();
                bodyBuilder.HtmlBody = @"<b>This is bold and this is <i>italic</i></b> " + DateTime.Now.ToString();
                message.Body = bodyBuilder.ToMessageBody();

                using (var client = new SmtpClient())
                {
                    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    await client.ConnectAsync("smtp.gmail.com", 465, true).ConfigureAwait(false);
                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    // Note: only needed if the SMTP server requires authentication
                    await client.AuthenticateAsync("YourEmailId", "EmailPassword").ConfigureAwait(false);
                    await client.SendAsync(message).ConfigureAwait(false);
                    await client.DisconnectAsync(true).ConfigureAwait(false);
                }
            });

            return new string[] { "value1", "value2" };
        }
    }
}
Dot Net Core Send Email Using MailKit Dot Net Core Send Email Using MailKit Reviewed by Bhaumik Patel on 8:33 PM Rating: 5