Quantcast
Channel: Web API
Viewing all articles
Browse latest Browse all 4850

Send Email controller example

$
0
0

I am looking for an example of how to send an email with webapi. I have ones  I use with mvc just sending through gmail and gmail sent me a message saying it was an unauthorized/insecure attempt by some app trying to send email??

public async Task<ActionResult> Contact(Email model)
        {
            // uses web.config for credentials
            if (ModelState.IsValid)
            {
                var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
                var message = new MailMessage();
                message.To.Add(new MailAddress("a@gmail.com"));
                message.From = new MailAddress("a@gmail.com");
                message.Subject = "Message from A.info";
                message.Body = string.Format(body, model.FromName, model.FromEmail, model.Message);
                message.IsBodyHtml = true;

                using (var smtp = new SmtpClient())
                {
                    await smtp.SendMailAsync(message);
                    return RedirectToAction("Index");
                }
            }
            return View(model);

        }

In the web config I have the login details

<system.net><mailSettings><smtp from="a@gmail.com"><network host="smtp.gmail.com"
                 port="587"
                 userName="a@gmail.com"
                 password="password"
                 enableSsl="true"/></smtp></mailSettings></system.net>

How can I make this into a webapi controller that would send as i have tried a few things and can't seem to get it to send.

I do have a model class that I have not included and it works for mvc but not webapi??


Viewing all articles
Browse latest Browse all 4850


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>