Google Smtp Auth

Google Smtp Auth

// CsProj Api
    <PackageReference Include="MailKit" Version="4.12.0" />
    <PackageReference Include="Google.Apis.Auth" Version="1.69.0" />

Email method

using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
using Google.Apis.Auth.OAuth2.Flows;

 [HttpPost("{dbname}/{credtype}")]
        public async Task<ActionResult> SendEmailGoogle(string dbname, ReceiverEmail _ReceiverEmail, string credtype)
        {
            var companydata = await _IUtilityMethodsRepository.GetCompanyMstInfo(dbname);

            var senderinfo = await _IEmailRepository.GetSenderEmailCredentials(dbname);
            if (credtype == "S") // S - System, C - Client
            {
                senderinfo = await _IEmailRepository.GetSenderEmailCredentials("erpcrew");
            }

            _ReceiverEmail.msgcode = 2;

            if (senderinfo != null)
            {
                // OAuth 2.0 Gmail SMTP Authentication
                string clientId = "819846345184-rh6nf91lnb2ls10hd24rjk9kac5ct16s.apps.googleusercontent.com";
                string clientSecret = "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";
                string refreshToken = "YOUR_REFRESH_TOKEN"; // You should securely store this refresh token.

                // Refresh the access token using the refresh token
                var tokenResponse = new Google.Apis.Auth.OAuth2.Responses.TokenResponse
                {
                    RefreshToken = refreshToken
                };
                
                var credentials = new UserCredential(
                    new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                    {
                        ClientSecrets = new ClientSecrets
                        {
                            ClientId = clientId,
                            ClientSecret = clientSecret
                        }
                    }),
                    "user",
                    tokenResponse);

                bool success = await credentials.RefreshTokenAsync(CancellationToken.None);
                
                string accessToken = credentials.Token.AccessToken;
                

                // Initialize SmtpClient using System.Net.Mail
                var smtpClient = new SmtpClient("smtp.gmail.com")
                {
                    Port = 587,
                    EnableSsl = true,
                    Credentials = new NetworkCredential("contact@erpcrystal.co.in", accessToken) // Use OAuth2 access token
                };

                // Prepare the email message
                var mailMessage = new MailMessage
                {
                    From = new MailAddress(senderinfo.mailfrom, companydata.CompanyName),
                    Subject = _ReceiverEmail.emailsubject,
                    Body = _ReceiverEmail.emailmessage,
                    IsBodyHtml = true
                };

                // Add recipients
                if (!string.IsNullOrEmpty(_ReceiverEmail.email1)) mailMessage.To.Add(_ReceiverEmail.email1);
                if (!string.IsNullOrEmpty(_ReceiverEmail.email2)) mailMessage.To.Add(_ReceiverEmail.email2);
                if (!string.IsNullOrEmpty(_ReceiverEmail.email3)) mailMessage.To.Add(_ReceiverEmail.email3);
                if (!string.IsNullOrEmpty(_ReceiverEmail.email4))
                {
                    string[] Multi = _ReceiverEmail.email4.Split(';');
                    foreach (string multiemail in Multi)
                    {
                        if (multiemail.Length > 0)
                        {
                            mailMessage.To.Add(new MailAddress(multiemail.Replace("\r\n", "")));
                        }
                    }
                }

                // If there's an attachment
                if (!string.IsNullOrEmpty(_ReceiverEmail.emailfilename))
                {
                    string pathname = "\\MFGReports\\Reports\\" + dbname + "\\" + _ReceiverEmail.emailfilename;
                    if (credtype == "S")
                    {
                        pathname = "\\MFGReports\\Docs\\" + dbname + "\\" + _ReceiverEmail.subfoldername + "\\" + _ReceiverEmail.emailfilename;
                    }

                    var pathfilename = Path.GetFullPath(pathname);

                    // Attach the file
                    var attachment = new Attachment(pathfilename);
                    mailMessage.Attachments.Add(attachment);

                    // Send the email with attachment
                    smtpClient.Send(mailMessage);
                    attachment.Dispose();
                    _ReceiverEmail.msgcode = 1; // Success
                }
                else
                {
                    // Send email without attachment
                    smtpClient.Send(mailMessage);
                    _ReceiverEmail.msgcode = 1; // Success
                }
            }

            return Ok(_ReceiverEmail);
        }