0
votes

I am trying to send email with my office 365 credentials using C#. But It is failing to send and getting exception.

How to fix this? Is it possible to send from office 365?

     foreach (var filename in files)
     {
           String userName = "[email protected]";
           String password = "password";
           MailMessage mail = new MailMessage();
           SmtpClient SmtpServer = new SmtpClient("smtp.office365.com");
           mail.From = new MailAddress("[email protected]");
           mail.To.Add("[email protected]");
           mail.Subject = "Fwd: for " + filename;
           mail.Body = "mail with attachment";

           System.Net.Mail.Attachment attachment;
           attachment = new System.Net.Mail.Attachment(filename);
           mail.Attachments.Add(attachment);

           SmtpServer.Port = 587;
           SmtpServer.Credentials = new System.Net.NetworkCredential(userName, password);
           SmtpServer.EnableSsl = true;

           SmtpServer.Send(mail);
}

Transaction failed. The server response was: 5.2.0 STOREDRV.Submission.Exception:SendAsDeniedException.MapiExceptionSendAsDenied; Failed to process message due to a permanent exception with message Cannot submit message.

1
Is this [email protected] hosted on Office 365 online tenant?TiagoBrenck
yes. I have Office 365 online account.James123

1 Answers

0
votes

How many emails are you going to send simultaneously?

foreach (var filename in files)

All Outlook APIs accessed via https://outlook.office.com/api or https://outlook.office365.com/api have a limit is 60 requests per minute, per user (or group), per app ID. So, for now, developers only can make limited APIs calls from the app. Read through the Microsoft Blog Post for more details on REST API call limitations.

Try to use the following code instead:

MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("[email protected]", "SomeOne"));
msg.From = new MailAddress("[email protected]", "You");
msg.Subject = "This is a Test Mail";
msg.Body = "This is a test message using Exchange OnLine";
msg.IsBodyHtml = true;

SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("your user name", "your password");
client.Port = 587; // You can use Port 25 if 587 is blocked (mine is!)
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
try
{
    client.Send(msg);
    lblText.Text = "Message Sent Succesfully";
}
catch (Exception ex)
{
    lblText.Text = ex.ToString();
}