Tuesday, 21 March 2017

Emailing an attachment in C# through Office 365

Scenario: You want to send an email with attachment in C#, using an Office 365 account.

Solution:

SmtpClient client = new SmtpClient("smtp.outlook.office365.com");
client.Port = 587;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("user@callerip.ca", "passwwrd");
client.Credentials = cred;
                

MailAddress from = new MailAddress("user@contoso", "Caller IP");
MailAddress toEmail = new MailAddress("toaddress@email.com");
MailMessage mm = new MailMessage(from, toEmail);
mm.Subject = "Your subject";
mm.Body = "Message in email body.";
Attachment a = new Attachment(filename);
mm.Attachments.Add(a);
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.Send(mm);

No comments:

Post a Comment