How to send email from webapi using c#

To Configure or send email from a web application or a web services, we can use the below code. 

Here, we are configuring the mail settings in web config file, the configuration includes host,username,password and sender mail id.
 
Step 1: Add the below code in web-config



Step 2:Paste the below code in web API controller

        [HttpGet]
        [Route("send-email")]
        public async Task SendEmail()
        {
            var message = new MailMessage();
            message.To.Add(new MailAddress("Abhinay" + " <" + "receivermailid@gmail.com" + ">"));
            message.From = new MailAddress("AbhinayKumar ");
            message.Bcc.Add(new MailAddress("AbhinayKumar "));
            message.Subject = "test message";
            message.Body = createEmailBody("receiver name", "message text");
            message.IsBodyHtml = true;
            using (var smtp = new SmtpClient())
            {
                await smtp.SendMailAsync(message);
                await Task.FromResult(0);
            }
        }

        private string createEmailBody(string userName, string message)
        {
            string body = string.Empty;
            using (StreamReader reader = new                       StreamReader(HttpContext.Current.Server.MapPath("/htmlTemplate.html")))
            {
                body = reader.ReadToEnd();
            }
            body = body.Replace("{UserName}", userName);
            body = body.Replace("{message}", message);
            return body;
        }



The output will be as shown below,





Popular posts from this blog

Top MNC Interview Questions- Full Stack Developer

Interview Questions-2

How to get the user details, user current level, next level, Rank in sql server