Azure : Function App

Azure : Function App



Here is sample code to send email using Azure function app

Encryption


namespace DemoFunctionApp
{
    public class EmailUsers
    {
        public string ToEmail { get; set; }
    }

    public class Response
    {
        public string StatusCode { get; set; }
        public string Message { get; set; }
        public string Data { get; set; }

    }
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            var mailmessage = new MailMessage { From = new MailAddress("user@gmail.com", "UserName") };

            var emailUsers = await req.Content.ReadAsAsync<EmailUsers>();
            
            mailmessage.To.Add(emailUsers.ToEmail);

            mailmessage.Subject = "Test email from function app" + System.DateTime.Now;
            mailmessage.IsBodyHtml = true;
            mailmessage.Body = "TEst email from function app" + System.DateTime.Now;

            SmtpClient smtpClient = null;
            smtpClient = new SmtpClient();

            smtpClient.Host = "smtp.gmail.com";
            smtpClient.Port = 587;
            smtpClient.UseDefaultCredentials = false;

            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpClient.Credentials = new NetworkCredential("user@gmail.com", "userEmailPassword");

            smtpClient.EnableSsl = true;

            smtpClient.Send(mailmessage);

            Response response = new Response
            {
                StatusCode = HttpStatusCode.OK.ToString(),
                Message = "Success",
                Data = emailUsers.ToEmail
            };

            return req.CreateResponse(HttpStatusCode.OK, response);
        }
    }
}

Hope this will help you and save your time.

Enjoy !!!

:)

No comments:

Post a Comment