19 Januar 2016

How to Send Mails in ASP .NET 5 on Azure

Unfortunately neither SendGrid nor System.Net.Mail is supported in the actual version of ASP .NET 5 (RC).

So how to send mails then?
One solution is to use MailKit https://github.com/jstedfast/MailKit

To use MailKit just add "MailKit": "1.3.0-beta5" to your project.json

What you need is an SMTP server. On Azure you can create a SendGrid account and use the host name and the credentials provided in the Configurations section. SendGrid on Azure is free for up to 25'000 mails per month!

The code to send a mail is straight forward.

private void SendEmail()
{
  var message = new MimeMessage();
  message.From.Add(new MailboxAddress("Peter Muster", "peter@muster.ch"));
  message.To.Add(new MailboxAddress("Petra Muster", "petra@muster.ch"));
  message.Subject = "Some Subject";

  message.Body = new TextPart("plain")
  {
    Text = string.Format(@"Hello,

Just a little message for you"
  };

  using (var client = new SmtpClient())
  {
    client.Connect("smtp.sendgrid.net", 587, false);
    client.AuthenticationMechanisms.Remove("XOAUTH2");
    client.Authenticate("your_id@azure.com", "password");

    client.Send(message);
    client.Disconnect(true);
  }
}


Kommentare:

Majo Mikula hat gesagt…

Hello, super it works. Do you know how can I use google smtp? Because I have problem with gmail smtp in azure... Thanks

Simon Martinelli hat gesagt…

Hi Majo,

Never tried with Google Mail but this should work as well.
Do you get an error message?

Rose Ferriams hat gesagt…

Die am häufigsten verwendeten apps sind http://www.munsoft.de/EasyOutlookRecovery/ Diese Software hilft gelöschte Nachrichten wieder herstellen .