Send email using ASP.Net MVC

2

How can I send email using ASP.Net MVC? Do you have any option to send without specifying SMTP similar to mail() of PHP ?

    
asked by anonymous 03.09.2015 / 22:20

2 answers

5

One form that I find interesting is this:

public bool Mail(MailAddress to, MailAddress from, string sub, string body) {
    var me = new EmailBusiness();
    var m = new MailMessage() {
        Subject = sub,
        Body = body,
        IsBodyHtml = true
    };
    to = new MailAddress("endereç[email protected]", "Nome");
    m.To.Add(to);
    m.From = new MailAddress(from.ToString());
    m.Sender = to;
    var smtp = new SmtpClient {
        Host = "url.do.servidor",
        Port = 587,
        Credentials = new NetworkCredential("usuario", "senha"),
        EnableSsl = true
    };
    try {
        smtp.Send(m);
    } catch (Exception e) { //não faça isto, por favor, é só um exemplo
        return false
    }
    return true;
}

I found it in answer in SO and adapted it. There is more information if you want to include it in an ASP.Net MVC application. But I understand that the focus of the question is the submission itself and not the ASP.Net MVC. Obviously it can be improved.

The question and the other answer on the same page has a slightly different form.

Note that mail() of PHP uses an SMTP server. You can not send without having one. Unless you write code or grab a library that is an SMTP server. This is usually not a good idea.

    
03.09.2015 / 22:34
5

Yes. For example, SendGrid . I put a helper on it like this:

public static class SendGridHelper
{
    public static async Task EnviarEmail(String assunto, String mensagemHtml, String mensagemText)
    {
        // Cria o objeto de e-mail
        var myMessage = new SendGridMessage();

        // Remetente
        myMessage.From = new MailAddress("[email protected]");

        List<String> recipients = new List<String>
            {
                @"Cigano Morrison Mendez <[email protected]>"
            };

        myMessage.AddTo(recipients);
        myMessage.Subject = assunto;

        myMessage.Html = mensagemHtml;
        myMessage.Text = mensagemText;

        // Você pode mandar por credenciais...
        // var username = "usuario";
        // var pswd = "senha";
        // var credentials = new NetworkCredential(username, pswd);
        //var transportWeb = new Web(credentials);

        // ...ou por chave de API
        var transportWeb = new Web("MinhaChaveDeApi");

        // Finalmente, envia.
        await transportWeb.DeliverAsync(myMessage);
    }
}

SendGrid is free for up to 12,000 emails . It has management panel and is very resilient to spam.

    
03.09.2015 / 22:34