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

Implement virtualisation in kendo drop down list using jquery ajax in mvc, aspx page

How to Create trigger to Update the NoofOrgs Count under each category in Category Table based on Temp Table in Sql Server

How to Preview the image and download which is in base64string format in mvc view using C#