Search code examples
c#asp.net-mvcemailrazor-pages

Sending / creating an email from an ASP.NET MVC web applicaiton through an Exchange Server


I'm trying to send an email from my ASP.NET MVC web application, which is quite looking easy when using Mailkit nuget package.

The tricky part is when you try to send this email from inside an organisation, which means that I won't use any "public" smtp server.

This is the code I've tried:

// send email
using var smtp = new SmtpClient();
smtp.Connect("smtp.ethereal.email", 587, SecureSocketOptions.StartTls);
smtp.Authenticate("[USERNAME]", "[PASSWORD]");
smtp.Send(email);
smtp.Disconnect(true);

This is coming from website: https://jasonwatmore.com/post/2022/03/11/net-6-send-an-email-via-smtp-with-mailkit

The problem is that from inside a company network, the stmp server is not reachable, to perform some testing.

My question is how to configure this to be usable within a company exchange server setting?

I've searched the web, but all I could find only refers to public smtp settings (google, outlook365 and so on...)

Thanks for your help


Solution

  • I finally found how to do that, thanks to a LinkedIn post about FluentEmail, that helped me a lot, in the meantime I have found details of the Exchange server, the code I use is this one:

    var sender = new SmtpSender(() => new SmtpClient("smtp.ofYourExchangeServer.com")
                {
                    EnableSsl = false,
                    //DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory,
                    //PickupDirectoryLocation = @"C:\MyEmail"
    
                    UseDefaultCredentials = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    Port = YourServerPortNumber,
                }) ;
    
    var email = await Email
                    .From("[email protected]", "Your Name")
                    .To("[email protected]", "Recipient Name")
                    .Subject("Thanks!")
                    //.UsingTemplate(template.ToString(), new { FirstName = "xxx" })
                    
                    //.Body("Thanks For your email.")
                    .AttachFromFilename(@"path\to\your\attached\file")
                    .SendAsync();
    

    Using this code allows the email to be sent directly and silently.

    I hope this will help