asp.net-mvc – Send email using ASP.NET

Question:

I would like to know how to send an email using ASP.NET. The idea will be to click on a button called send and send an email from suportcegos@sapo.pt (personal) to nsoares@cegoc.pt (business). Thanks.

Answer:

Here is an example with asp.net mvc4 and javascript:

MVC:

public ActionResult SendEmail()
{
    var fromAddress = new System.Net.Mail.MailAddress("from@gmail.com", "From Name");
    var toAddress = new System.Net.Mail.MailAddress("to@example.com", "To Name");
    const string fromPassword = "fromPassword";
    const string subject = "Subject";
    const string body = "Body";

    var smtp = new System.Net.Mail.SmtpClient
    {
        Host = "smtp.gmail.com",
        Port = 587,
        EnableSsl = true,
        DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new System.Net.NetworkCredential(fromAddress.Address, fromPassword)
    };
    using (var message = new System.Net.Mail.MailMessage(fromAddress, toAddress)
    {
        Subject = subject,
        Body = body
    })
    {
        smtp.Send(message);
    }
    return View("Index");
}

HTML:

<a href="javascript:;" class="btn btn-primary" id="enviar">Enviar</a>

Javascript:

<script type="text/javascript">

        $("#enviar").click(function () {
            $.ajax({
                url: '@Url.Action("SendEmail", "Home")',
                type: 'POST',
                data: { },
                success: function (result) {
                    alert('Um email foi enviado com sucesso');
                }
            });
        });
</script>
Scroll to Top
AllEscort