I have implemented email service for my website in ASP .NET. This is my code
private async Task SendEmailInternalAsync(SendEmailDto sendEmailDto)
{
// create message
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse(sendEmailDto.From));
email.To.Add(MailboxAddress.Parse(sendEmailDto.To));
email.Subject = sendEmailDto.Subject;
email.Body = new TextPart(TextFormat.Html) { Text = sendEmailDto.Html };
try
{
var emailPrivateKey = Configuration.GetConnectionString("EmailPrivateKey");
var credential = new ServiceAccountCredential(new ServiceAccountCredential
.Initializer("x@y.iam.gserviceaccount.com")
{
// Note: other scopes can be found here: https://developers.google.com/gmail/api/auth/scopes
Scopes = new[] { "https://mail.google.com/" },
User = sendEmailDto.From
}.FromPrivateKey(emailPrivateKey));
bool result = await credential.RequestAccessTokenAsync(CancellationToken.None);
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
// use the access token
var oauth2 = new SaslMechanismOAuth2(sendEmailDto.From, credential.Token.AccessToken);
client.Authenticate(oauth2);
client.Send(email);
client.Disconnect(true);
}
}
catch (Exception e)
{
_logger.LogError(e, "Failed during sending email.");
}
}
It is working just fine but causing a very weird problem. When I am sending the email outside my domain, It is taking exactly 5 minutes to show in the inbox. When I am sending the email to my domain emails, it is going instantly.
After few observation, The main thing I observed is the time which email is showing is exactly same time when I sent the mail but It is only showing in inbox after 5 minutes. Let me explain this with more clearly.
Let's say I am sending the mail at 2:48 pm. I receive the mail in my inbox at exactly 2:53pm but the interesting thing is gmail is showing the time 2:48pm only!!!
