-1

I have gmail API service account details = client id and service account. How can I just send an email from one id to other without OAuth?

I want to authorize this email sending process with the service account credentials only.

Is there a nuget package that can help fulfill this requirement?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Shashank Jain
  • 61
  • 1
  • 7
  • What do you mean by "from one id to other"? Note that (generally speaking) you cannot send email _on behalf of someone else_ over the Internet without the user granting you some kind of delegation permission through their e-mail provider. (Also watch-out for things like SPF, DKIM, etc, which will all lead to your outbound e-mails being flagged as spam unless you do things properly...) – Dai Sep 11 '21 at 08:34
  • "with the service account credentials only." - what exactly do you mean by "service account credentials"? If you mean Windows Service Account then that's entirely unrelated (unless you're using an on-prem MX/MTA like Microsoft Exchange). – Dai Sep 11 '21 at 08:37
  • Please elaborate on why you mentioned OAuth - while GMail does support OAuth, that still requires _your_ application code to be granted permission to a user's mailbox by the user themselves (which in-turn implies that your application will be issued an `access_token` by GMail) - you cannot use `client_credentials` in OAuth2 to send email on behalf of anyone in GMail: **"no shirt, no shoes, no `access_token`, no service"**. – Dai Sep 11 '21 at 08:39
  • @Dai this is not true with a service account properly configured via a google workspace account you can it can send emails on behalf of a workspace user. [delegate_settings](https://developers.google.com/gmail/api/guides/delegate_settings?hl=en) – Linda Lawton - DaImTo Sep 11 '21 at 11:40

1 Answers1

1

How can I just send an email from one id to other without OAuth?

I assume what you mean is how to send an email with out poping up the Oauth2 consent screen.

Using a service account will allow you to do that, once you have configured the permissions properly in your google workspace account. You grant the service account to preform actions on behalf of one of your domain users. This way the service account can send emails as that user without the user having to consent to that access because you have pre authorized it via google workspace.

The following code will show you how to authorize your application to use a service account.

class Program
    {
        public static string Base64Encode(string plainText)
        {
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
            return System.Convert.ToBase64String(plainTextBytes);
        }

    public static void SendMail()
    {
        try
        {
            string ApplicationName = "Gmail API .NET Quickstart";
            const string serviceAccount = "xxxx@xxxx-api.iam.gserviceaccount.com";

            var certificate = new X509Certificate2(@"c:\XXXX.p12", "notasecret", X509KeyStorageFlags.Exportable);

            var gsuiteUser = "YourDomain@YourDomain.com";

            var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(serviceAccount)
            {
                User = gsuiteUser,
                Scopes = new[] { GmailService.Scope.GmailSend, GmailService.Scope.GmailLabels }

            }.FromCertificate(certificate);

            var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer);
            if (!credential.RequestAccessTokenAsync(CancellationToken.None).Result)
                throw new InvalidOperationException("Access token failed.");

            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            var mailMessage = new MailMessage();
            mailMessage.From = new MailAddress("se@Yourdomain.com");
            mailMessage.To.Add("ddddd@hotmail.com");
            mailMessage.ReplyToList.Add("se@Yourdomain.com");
            mailMessage.Subject = "test";
            mailMessage.Body = "<h1>sdf</h1>";
            mailMessage.IsBodyHtml = true;

            //foreach (System.Net.Mail.Attachment attachment in email.Attachments)
            //{
            //    mailMessage.Attachments.Add(attachment);
            //}

            var mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mailMessage);

            var gmailMessage = new Message
            {
                Raw = Base64Encode(mimeMessage.ToString())
            };

            Message message1 = new Message();
            UsersResource.MessagesResource.SendRequest sendRequest = service.Users.Messages.Send(gmailMessage, "me");
            var s = sendRequest.Execute();


            Console.WriteLine("Message delivered!");
        }
        catch (Exception ep)
        {
            Console.WriteLine(ep.ToString());
        }
    }

The trick is to remember to set up the domain wide delegation properly and to decide which user the service account is going to be impersonating and to remember to add that email

without google workspace

If you do not have a google workspace account then you can not use service accounts. You may want to consider going though the smtp server instead.

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • I am getting this error message: System.AggregateException: One or more errors occurred. (Error:"invalid_grant", Description:"Invalid JWT Signature.", Uri:"") @DalmTo – Shashank Jain Sep 13 '21 at 08:21
  • Invalid grant with a service account sounds strange. any chance you want to regenerate the p12 file? And your sure you set up the delegation on your workspace account properly? – Linda Lawton - DaImTo Sep 13 '21 at 09:09
  • Is there any way I can manually make p12 certificate on windows? I have the service account details. But I cannot regenerate the p12 certificate. @DalmTo – Shashank Jain Sep 13 '21 at 09:14
  • the p12 must be created on Google cloud console its used to authorize to googles authorization server. check https://www.youtube.com/watch?v=asrCdWFrF0A remember you will need to create it from a user on your workspace domain. You cant use a standard gmail account to create it. – Linda Lawton - DaImTo Sep 13 '21 at 11:32
  • The service gmail has thrown an exception: Google.GoogleApiException: Google.Apis.Requests.RequestError Precondition check failed. [400] Errors [ Message[Precondition check failed.] Location[ - ] Reason[failedPrecondition] Domain[global] ] at Google.Apis.Requests.ClientServiceRequest`1.ParseResponse(HttpResponseMessage response) at Google.Apis.Requests.ClientServiceRequest`1.Execute() @DaImTo – Shashank Jain Sep 13 '21 at 11:43
  • DId you create it using a email from your worskpace domain? You can only use service accounts with gmail if its a workspace account. Delegation needs to be set up properly. Contact the admin of your workspace domain have them help you set it up. – Linda Lawton - DaImTo Sep 13 '21 at 11:47