简体   繁体   中英

Office 365 email configuration throws an exception

So my company has moved from gmail to outlook. I also had to change my code for the online store to be able to send emails to certain email addresses, but it doesn't. I think I have set everything correctly on my code, this is what i have.

NB: With Gmail suite this code perfomed exceptionally well, until migration to Office 365. and with this it only worked once, after that it never worked again

The username and password have been set.

namespace Reco.classes
{

public class Email
{
    classes.Common xCommon = new classes.Common();
    //classes.SQL xSQL = new classes.SQL();
    classes.ShoppingCart xShoppingCart = new classes.ShoppingCart();
    classes.Data xData = new classes.Data();


    const string Office365_Username = "";
    const string Office365_Password = "";
    const string msgFrom = "";

    string sExtOrderNum, sCustName, sCustDelAddress, sCustEmail, sCustNo;

    public void ContactUs_Email(string Name, string Email, string Contact_No, string Region, string Town, string Division, string ProductName, string ProductType, string ApplianceType, string ModelNumber, string Description, string PartNumber, string Type, string Contact_Message, string sBranchMailTo)
    {
        //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        SmtpClient smtpClient = new SmtpClient();  //smtp server name
        MailMessage myEmail = new MailMessage();

        string str = "";
        string FilePath = HttpContext.Current.Server.MapPath("~/email-template/contact-us.html");
        FileStream f1 = new FileStream(FilePath, FileMode.Open);
        StreamReader sr = new StreamReader(f1);
        str = sr.ReadToEnd();
        str = str.Replace("@Name", Name);
        str = str.Replace("@Email", Email);
        str = str.Replace("@Phone", Contact_No);
        str = str.Replace("@Region", Region);
        str = str.Replace("@Town", Town);
        str = str.Replace("@Division", Division);
        str = str.Replace("@ProductName", ProductName);
        str = str.Replace("@ProductType", ProductType);
        str = str.Replace("@ApplianceType", ApplianceType);
        str = str.Replace("@ModelNumber", ModelNumber);
        str = str.Replace("@Description", Description);
        str = str.Replace("@PartNumber", PartNumber);
        str = str.Replace("@Type", Type);
        str = str.Replace("@Message", Contact_Message);
        str = str.Replace("@DateTime", DateTime.Now.ToString("dd MMM yyyy : hh:mm"));

        f1.Close();

        try
        {
            
            string msgTo = "";
            //string msgCC = "";

            myEmail.IsBodyHtml = true;
            myEmail.Headers.Add("content-type", "text/html;");
            myEmail.From = new MailAddress(msgFrom);
            myEmail.To.Add(new MailAddress(msgTo));
            //myEmail.CC.Add(new MailAddress(msgCC));

            myEmail.Subject = "Website - Enquiries";
            myEmail.Body = str;

            //SmtpClient smtpClient = new SmtpClient();  //smtp server name
            smtpClient.EnableSsl = true;
            NetworkCredential NetworkCred = new NetworkCredential(Office365_Username, Office365_Password);
            smtpClient.UseDefaultCredentials = true;
            smtpClient.Credentials = NetworkCred;
            smtpClient.Port = 587;

            smtpClient.Send(myEmail);//throws exception here
            
        }
        catch (Exception ex)
        {
          System.Web.HttpContext.Current.Response.Write(ex.ToString());

        }
        finally
        {
            smtpClient = null;
            myEmail.Dispose();
            sr.Dispose();
        }

        

    }

web.config

<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" from="onlineshop@bluh.co.za">
      <network defaultCredentials="false" host="smtp.office365.com" port="587" enableSsl="true" userName="onlineshop@bluh.co.za" password="12345" />
    </smtp>
  </mailSettings>
  </system.net>

but this code throws this exception.

System.Net.Mail.SmtpException: Failure sending mail. ---> System.IO.IOException: Unable to read data from the transport connection:.net_io_connectionclosed. at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine) at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine) at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller) at System.Net.Mail.CheckCommand.Send(SmtpConnection conn, String& response) at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode) at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message)

--- End of inner exception stack trace ---

at System.Net.Mail.SmtpClient.Send(MailMessage message)

Thanks @jdweng,

So i only heard later that our 2 online mail boxes are coming from two different servers. Into my web.config, I had to add this code.

  <sectionGroup name="mailSettings">
    <section name="smtp_1" type="System.Net.Configuration.SmtpSection" />
    <section name="smtp_2" type="System.Net.Configuration.SmtpSection" />
  </sectionGroup>
</configSections>

<mailSettings>
  <smtp_1 deliveryMethod="Network" from="">
    <network defaultCredentials="false" host="" port="587"  enableSsl="true" userName="" password="" />
  </smtp_1>
  <smtp_2 deliveryMethod="Network" from="">
    <network defaultCredentials="false" host="" port="587"  enableSsl="true"  userName="" password="" />
  </smtp_2>
</mailSettings>

And then went on to declare in my code the changes added to the web.config file, ran a test and all was good. Then in my

Namespace email.classes 
//I added this lines of code for both onlineshop and Info

SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_1");
SmtpClient smtpClient = new SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port);  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM