I have a simple code used on multiple old website, code is used to send email notification when form is submitted. This code works fine. However IT admin want to enable Multi-Factor Authentication (MFA) for sender email which basically is office365 email address.
Below code will may work, as it may not impact MFA enablled email address as we are using this email to send email using code?
using System;
using System.Net;
using System.Net.Mail;
protected void SendEmail()
{
string fromEmail = "test@test.com";
string appPassword = "YourAppPassword"; // Use the App Password generated for the application
string toEmail = "recipient@example.com";
string subject = "Test Email";
string body = "This is a test email sent from ASP.NET WebForms.";
try
{
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(fromEmail);
mail.To.Add(toEmail);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient("smtp.office365.com", 587))
{
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential(fromEmail, appPassword); // Use the App Password
smtp.Send(mail);
}
Response.Write("Email sent successfully.");
}
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
}
}
After doing a research on this, its very much possible as pointed in some references however those reference documents refer to old versions of solution. So i am updating working solution with latest documentation available on MS. solution is pretty much same.
Code will remain same only you have to use App Password which can be created on https://mysignins.microsoft.com/security-info
Step 1: on login to your office365 website after MFA/2FA is enabled.
Step 2: go to security info tab and add new sign in method "+ Add sign-in method"
Step 3: Choose App Password method & complete the steps
Step 4: save the app password for use in code
smtp.Credentials = new NetworkCredential(fromEmail, appPassword);
This is all you need to do and code should work without any issues. I have tested this code multiple time to make sure you are able to send email.
One last point i would like to make is that after enabling the 2FA/MFA by IT Admin for this user, you should wait for at least 1 hours for changes to reflect globally as for me my code kept working for almost 10 minutes after 2FA was enabled without using App Password.