title: Gmail API Create and Send Email .NET C#
body: <h1>Problem</h1>
  <p>I am trying to implement the Gmail API into an API application. I created a service account and saved the p12 key and the json credentials. I am getting an exception talking about a failed precondition. I think it might have something to do with the message I'm trying to send.</p>
  <h1>Code</h1>
  <pre><code>String serviceAccountEmail = &quot;SERVICE-ACC-EMAIL&quot;;
  X509Certificate2 certificate = new X509Certificate2(&quot;./key.p12&quot;, &quot;notasecret&quot;, X509KeyStorageFlags.Exportable);
  // FileStream stream = new FileStream(&quot;./credentials.json&quot;, FileMode.Open, FileAccess.Read); // ! Not Used
              
  ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
  {
      User = serviceAccountEmail,
      Scopes = new[] { GmailService.Scope.MailGoogleCom }
  }.FromCertificate(certificate));
  GmailService service = new GmailService(new BaseClientService.Initializer()
  {
      HttpClientInitializer = credential,
      ApplicationName = &quot;Testing Application&quot;,
  }); 
  var result = service.Users.Messages.Send(CreateEmail.CreateEmailMessage(), &quot;me&quot;).Execute();
  </code></pre>
  <h1>Exception</h1>
  <pre><code>An unhandled exception of type 'Google.GoogleApiException' occurred in System.Private.CoreLib.dll: 'Google.Apis.Requests.RequestError
  Precondition check failed. [400]
  Errors [
      Message[Precondition check failed.] Location[ - ] Reason[failedPrecondition] Domain[global]
  ]'
  </code></pre>
  <h1>Building Mail Message (does not work)</h1>
  <p>In the CreateEmail.CreateEmailMessage method I build up a new instance of Google.Apis.Gmail.v1.Data.Message. Setting the payload and headers. Take this as reference. I am not sure if this is the way to do it but I can't seem to find a way to create a new message. All I can find is things written in Java or Python which i tried translating over to C#, failing spectacularly</p>
  <pre><code>var msg2 = new Message()
  {
      Payload = new MessagePart()
      {
          Body = new MessagePartBody()
          {
              Data = Convert.ToBase64String(Encoding.UTF8.GetBytes(&quot;Hello world&quot;))
          },
          Headers = new List&lt;MessagePartHeader&gt;() {
              new MessagePartHeader() { Name = &quot;To&quot;, Value = &quot;My email&quot;},
  ...
  </code></pre>