Send email using Office 365 account and C#
Microsoft Cloud offering “Office 365” is becoming popular day by day. One of the mostly used feature in Office 365 is the exchange online. Lots of customers are moving their emails to exchange online.
The developers now needs to send email notifications using Exchange online as their SMTP Server. Office 365 offers various integration options that allows your devices/applications to connect and send email. Refer the below technet article for more details.
https://technet.microsoft.com/en-us/library/dn554323(v=exchg.150).aspx
As a developer you need to send email from your applications frequently, for e.g. sending validation email after a user registration, a confirmation email after a product purchase etc. Office 365 supports client submission feature so that applications can send email using office 365 account. You can find more about the client submission feature in office 365 from the below URL.
https://technet.microsoft.com/en-us/library/dn554323(v=exchg.150).aspx#HowtoconfigSMTPCS
In order to send email using the “client submission” method, you need to have valid Office 365 credentials. Once you have the credentials with you, you can send the email using the below code.
String userName = "user@domain.com";
String password = "your password";
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("ToAddress"));
msg.From = new MailAddress(userName);
msg.Subject = "Test Office 365 Account";
msg.Body = "Testing email using Office 365 account.";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Host = "smtp.office365.com";
client.Credentials = new System.Net.NetworkCredential(userName, password);
client.Port = 587;
client.EnableSsl = true;
client.Send(msg);
Ideally you will store the username and password in a configuration file or in the database, then retrieve it from there. The code specified above is self-explanatory. Basically you need to specify the Host, Port, EnableSSL and the credentials properties of SmtpClient object. Both 587 and 25 are supported for port, however 587 is the recommended one.
In some situations you may need to specify a custom from address other than the user name you used. You can specify the from address as any email available under your domain, but you need to grant “Send Email from mailbox” permission for the email sending user account to the email you wish to specify as from address.
In some (most) cases you may need to specify more generic name such as no-reply@yourdomain.com. For this purpose, you can create shared mailbox that doesn’t require exchange online license (there is a size limit of 5GB, which will be adequate for such scenarios).