SMTP email through Microsoft 365 via C#

An example of how to use the System.Net namespace to send emails (useful for ssl or tls mail servers).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
SmtpClient server = new SmtpClient("Smtp.mail.microsoftonline.com");
server.Port = 587;
server.EnableSsl = true;
server.Credentials = new System.Net.NetworkCredential("[email protected]", "secret");

MailMessage mail = new MailMessage();
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "test subject";
mail.Body = "this is my message body";
mail.IsBodyHtml = true;

try
{
    server.Send(mail);
}
catch (Exception ex)
{
    throw ex;
}

Taken from here: http://stackoverflow.com/questions/6656039/sending-email-using-smtp-mail-microsoftonline-com/7009204#7009204

Leave a Reply