Send emails through Office365/Exchange Online using .NET
If your organization is using Office365 and Exchange Online, sending emails from your .NET code or websites is still pretty simple
Basically you have two options. You can either specify the email settings in your web.config or app.config file, or you can do it programmatically. In this quick post I will show you both ways.
Using configuration
Open your .config file, locate the system.net section and insert the following:
<system.net>
<mailSettings>
<smtp>
<network defaultCredentials=”false” enableSsl=”true” host=”smtp.office365.com” port=”587" password=”MyPassword" userName=”info@MyCompany.Com” /> </smtp>
</mailSettings>
</system.net>
If you are already using the .config file in your applications, you can see that the change is very minimal. Office365 uses the non-standard port 587, but other than that, it is pretty straight-forward.
Sending mail from code
You can specify the settings directly on the SmtpClient object in .NET. This example uses C# to send out a simple email:
MailMessage mail = new MailMessage(“info@MyCompany.com”,”some@user.net”);
mail.IsBodyHtml = true;
mail.Subject = “An email from Office365”;
mail.Body = “<html><body><h1>Hello world</h1></body></html>”;
SmtpClient client = new SmtpClient(“smtp.office365.com”);
client.Port = 587;
client.EnableSsl = true;
client.UseDefaultCredentials = false; // Important: This line of code must be executed before setting the NetworkCredentials object, otherwise the setting will be reset (a bug in .NET)
NetworkCredential cred = new System.Net.NetworkCredential(“info@MyCompany.com”, “MyPassword"); client.Credentials = cred;
client.Send(mail);
Remember your ‘Send as’ permissions
If your FROM address (user) is different from the user you use as the Sign-In user in your NetworkCredentials, you need to make sure that the Sign-In user has “Send As” permissions for the FROM user’s mailbox.
This can be done the following way:
- Login to https://portal.microsoftonline.com user an Admin User
- Select the Admin — Exchange menu
- Click on the Recipients link on the left navigation
- Go to the Recipients list and double-click on the FROM user
- Select the Mailbox delegation link
- Click on the “+” button and add the account you use in your NetworkCredentials