Smtp OAuth 2.0
Email Controller
using MailKit.Net.Smtp;
using MailKit.Security;
using MailKit;
using MimeKit;
using Microsoft.Identity.Client;
using System.Net.Http.Headers;
using System.ComponentModel.DataAnnotations;
[HttpPost("{dbname}/{credtype}")]
public async Task<ActionResult> SendEmailAuth2(string dbname, ReceiverEmail _ReceiverEmail, string credtype)
{
// <PackageReference Include="MailKit" Version="4.12.0" />
// <PackageReference Include="Microsoft.Identity.Client" Version="4.71.1" />
var companydata = await _IUtilityMethodsRepository.GetCompanyMstInfo(dbname);
var senderinfo = await _IEmailRepository.GetSenderEmailCredentials(dbname);
if (credtype == "S")
{
senderinfo = await _IEmailRepository.GetSenderEmailCredentials("erpcrew");
}
_ReceiverEmail.msgcode = 2;
if (senderinfo != null)
{
// Get OAuth token
var clientId = "2cbc367c-ed76-4b58-b346-e460abc49b38";
var tenantId = "7fc68e96-5940-4ae4-a62b-d3f42afbb1e5";
var clientSecret = "rPX8Q~heG8qhlpInG~KwNFzNN2f2i9wpTvhDgbRs";
var confidentialClient = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority($"https://login.microsoftonline.com/{tenantId}")
.Build();
var result = await confidentialClient.AcquireTokenForClient(new[] {
"https://outlook.office365.com/.default"
}).ExecuteAsync();
var accessToken = result.AccessToken;
using var smtp = new MailKit.Net.Smtp.SmtpClient();
await smtp.ConnectAsync("smtp.office365.com", 587, SecureSocketOptions.StartTls);
var oauth2 = new SaslMechanismOAuth2(senderinfo.username, accessToken);
var MailInfo = new MimeMessage();
MailInfo.From.Add(new MailboxAddress(companydata.CompanyName, senderinfo.mailfrom));
if (!string.IsNullOrEmpty(_ReceiverEmail.email1))
{
MailInfo.To.Add(MailboxAddress.Parse(_ReceiverEmail.email1));
}
if (!string.IsNullOrEmpty(_ReceiverEmail.email2))
{
MailInfo.To.Add(MailboxAddress.Parse(_ReceiverEmail.email2));
}
if (!string.IsNullOrEmpty(_ReceiverEmail.email3))
{
MailInfo.To.Add(MailboxAddress.Parse(_ReceiverEmail.email3));
}
if (!string.IsNullOrEmpty(_ReceiverEmail.email4))
{
foreach (string multiemail in _ReceiverEmail.email4.Split(';'))
{
if (multiemail.Length > 0)
{
MailInfo.To.Add(MailboxAddress.Parse(multiemail.Replace("\r\n", "")));
}
}
}
MailInfo.Subject = _ReceiverEmail.emailsubject;
var builder = new BodyBuilder { HtmlBody = _ReceiverEmail.emailmessage };
string pathname = "";
if (!string.IsNullOrEmpty(_ReceiverEmail.emailfilename))
{
pathname = "\\MFGReports\\Reports\\" + dbname + "\\" + _ReceiverEmail.emailfilename;
if(credtype == "S")
{
pathname = "\\MFGReports\\Docs\\" + dbname + "\\" + _ReceiverEmail.subfoldername + "\\" + _ReceiverEmail.emailfilename;
}
var pathfilename = Path.GetFullPath(pathname);
builder.Attachments.Add(pathfilename);
}
MailInfo.Body = builder.ToMessageBody();
await smtp.AuthenticateAsync(oauth2);
await smtp.SendAsync(MailInfo);
await smtp.DisconnectAsync(true);
if (!string.IsNullOrEmpty(pathname))
System.IO.File.Delete(pathname);
_ReceiverEmail.msgcode = 1;
}
return Ok(_ReceiverEmail);
}
[HttpPost("{dbname}/{credtype}")]
public async Task<ActionResult> SendEmailAuth2GraphApi(string dbname, ReceiverEmail _ReceiverEmail, string credtype)
{
var companydata = await _IUtilityMethodsRepository.GetCompanyMstInfo(dbname);
var senderinfo = await _IEmailRepository.GetSenderEmailCredentials(dbname);
if (credtype == "S")
{
senderinfo = await _IEmailRepository.GetSenderEmailCredentials("erpcrew");
}
_ReceiverEmail.msgcode = 2;
if (senderinfo != null)
{
// Get OAuth token
var clientId = "2cbc367c-ed76-4b58-b346-e460abc49b38";
var tenantId = "7fc68e96-5940-4ae4-a62b-d3f42afbb1e5";
var clientSecret = "rPX8Q~heG8qhlpInG~KwNFzNN2f2i9wpTvhDgbRs";
var confidentialClient = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority($"https://login.microsoftonline.com/{tenantId}")
.Build();
var result = await confidentialClient.AcquireTokenForClient([
"https://graph.microsoft.com/.default"
]).ExecuteAsync();
var accessToken = result.AccessToken;
// Prepare email message
var emailMessage = new
{
message = new
{
subject = _ReceiverEmail.emailsubject,
body = new { contentType = "HTML", content = _ReceiverEmail.emailmessage },
toRecipients = new List<object>(),
attachments = new List<object>(),
from = new {
emailAddress = new {
name = companydata.CompanyName, // Display name shown to the recipient
address = senderinfo.mailfrom // Actual email address used to send
}
}
},
saveToSentItems = true
};
_ReceiverEmail.email1 = "udit@erpcrystal.in";
_ReceiverEmail.email2 = "udit@erpcrystal.in";
_ReceiverEmail.email3 = "udit@erpcrystal.in";
// **Handle Multiple Recipients**
foreach (var email in new[] { _ReceiverEmail.email1, _ReceiverEmail.email2, _ReceiverEmail.email3 })
{
if (!string.IsNullOrEmpty(email))
{
emailMessage.message.toRecipients.Add(new { emailAddress = new { address = email } });
}
}
if (!string.IsNullOrEmpty(_ReceiverEmail.email4))
{
foreach (string multiemail in _ReceiverEmail.email4.Split(';'))
{
if (!string.IsNullOrEmpty(multiemail))
{
emailMessage.message.toRecipients.Add(new { emailAddress = new { address = multiemail.Trim() } });
}
}
}
// **Handle Attachments**
string pathname = "";
if (!string.IsNullOrEmpty(_ReceiverEmail.emailfilename))
{
pathname = $"\\MFGReports\\Reports\\{dbname}\\{_ReceiverEmail.emailfilename}";
if (credtype == "S")
{
pathname = $"\\MFGReports\\Docs\\{dbname}\\{_ReceiverEmail.subfoldername}\\{_ReceiverEmail.emailfilename}";
}
var fileBytes = System.IO.File.ReadAllBytes(Path.GetFullPath(pathname));
var base64File = Convert.ToBase64String(fileBytes);
emailMessage.message.attachments.Add(new
{
name = _ReceiverEmail.emailfilename,
contentBytes = base64File,
contentType = "application/octet-stream"
});
}
// **Send Email via Graph API**
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
// var IsValid = await httpClient.GetFromJsonAsync<dynamic>(@$"https://graph.microsoft.com/v1.0/users/udit@erpcrystal.in");
var response = await httpClient.PostAsJsonAsync(@$"https://graph.microsoft.com/v1.0/users/{_ReceiverEmail.email1}/sendMail", emailMessage);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"Error sending email: {response.StatusCode}");
return BadRequest("Failed to send email.");
}
// Delete file after sending
System.IO.File.Delete(pathname);
_ReceiverEmail.msgcode = 1;
}
return Ok(_ReceiverEmail);
}Csproj web and api
<PackageReference Include="MailKit" Version="4.12.0" />
<PackageReference Include="Microsoft.Identity.Client" Version="4.71.1" />
<PackageReference Include="Microsoft.Graph" Version="5.77.0" />