Gmails OAUTH 2.0 without ServiceAccount

111 views Asked by At

I'm trying to send an Email with the OAUTH 2.0 authentication like this:

        var certificate = new X509Certificate2(@"C:\path\to\my.p12", "mypassword", X509KeyStorageFlags.Exportable);

        var credential = new ServiceAccountCredential(new ServiceAccountCredential
            .Initializer("[email protected]")
        {
            Scopes = new[] { "https://mail.google.com/" },
            User = "[email protected]"
        }.FromCertificate(certificate));

        bool result = await credential.RequestAccessTokenAsync(CancellationToken.None);


        // send email
        using (var client = new SmtpClient())
        {
            client.Connect("smtp.gmail.com", 587, false);
            client.Authenticate("user.name", credential.Token.AccessToken);
            client.Send(myMessage);
            client.Disconnect(true);
        }

But when I'm running this code I get the TokenResponseException: "Client is unauthorized to retrieve access tokens using this method." Am I right that I need to authorize my client, what is only possible with a G Suit account? So I have to pay for an Admin account or remove the OAUTH?

1

There are 1 answers

3
jstedfast On BEST ANSWER

You need to follow Google's instructions for obtaining OAuth 2.0 credentials for your application.