0

Getting the following error when trying to send from local dev environment for google API. Not sure the right way to attack it. Any advice would be appreciated. Here is the Full Text of the method I am working on.

This is all Google code.

private const string ApplicationName = "<FromGoogle>";
private const string SenderEmailAddress = "<FromGoogle>";
private const string ClientId = "<FromGoogle>";
private const string ClientSecret = "<FromGoogle>";

private static GmailService _service;
private static StringWriter _message;

public static Message SendMail(string subject, string body, params string[] recipients)
{
    string[] scopes = { GmailService.Scope.GmailCompose, GmailService.Scope.GmailSend };
    ClientSecrets secrets = new ClientSecrets() { ClientId = ClientId, ClientSecret = 
        ClientSecret };
    string folder = HttpContext.Current.Server.MapPath("~/App_Data") + "/gmail-credentials.json";
    UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, 
        scopes, "user", CancellationToken.None, new FileDataStore(folder, true)).Result;
    _service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer 
        = credential, ApplicationName = ApplicationName });

    MailMessage msg = new MailMessage
    {
        Subject = subject,
        Body = body,
        From = new MailAddress(SenderEmailAddress)
    };

    foreach (var recipient in recipients) msg.To.Add(new MailAddress(recipient));
    msg.ReplyTo.Add(msg.From);
    _message = new StringWriter();
    msg.Save(_message);

    Message result = _service.Users.Messages.Send(new Message { Raw = 
        Base64UrlEncode(_message.ToString()) }, "me").Execute();
    return result;
}

private static string Base64UrlEncode(string input)
{
    var inputBytes = Encoding.UTF8.GetBytes(input);
    // Special "url-safe" base64 encode.
    return Convert.ToBase64String(inputBytes)
        .Replace('+', '-')
        .Replace('/', '_')
        .Replace("=", "");
}

I get the following exception

Exception thrown: 'Google.Apis.Auth.OAuth2.Responses.TokenResponseException' 
    in Google.Apis.dll

Additional information: Error:"invalid_grant", Description:"", Uri:""
Warwick Foster
  • 163
  • 1
  • 11
  • Can you show us some more code so we have additional context? – mjwills Jun 15 '17 at 14:04
  • Invalid grant usually means your app is trying to do something that it hasn't been given permission to do. Try looking at this answer: https://stackoverflow.com/questions/10576386/invalid-grant-trying-to-get-oauth-token-from-google – Doctor Jones Jun 15 '17 at 14:24

1 Answers1

0

In the end the code was correct. Turns out to be an authorisation issue with Google to which Doctor Jones referred.

After working through the code I changed the ClientId to the Client email. Google specifically did not like that and brought up a web page and told me I was denied.

When I put the code back as it was I ran the test below again and it brought up a google authorisation webpage and after having gone through that the tests were working.

[TestMethod()]
public void SendMailTest()
{
    string subject ="subject";
    string body = "body";
    string recipient = "test@test.com";

    Message result = null;

    try
    {
        result = MailTools.SendMail(subject, body, recipient);
    }
    catch (Exception ex)
    {
        Assert.Fail(ex.Message);
    } 

    result.ShouldNotBeNull();
}
Warwick Foster
  • 163
  • 1
  • 11