title: Gmail API Errors on SendEmail Using .NET Client Libraries
body: <p>Our web application uses the Google .Net Client libraries to send emails for our users. One particular user has had trouble sending emails; mainly with attachments. The 2 error messages that we seem to get are the following:</p>
  
  <blockquote>
    <p>The service gmail has thrown an exception: Google.GoogleApiException:
    Google.Apis.Requests.RequestError 'raw' RFC822 payload message string
    or uploading message via /upload/* URL required [400] Errors [
    Message['raw' RFC822 payload message string or uploading message via
    /upload/* URL required] Location[ - ] Reason[badRequest]
    Domain[global] ]</p>
  </blockquote>
  
  <p>And more recently:</p>
  
  <blockquote>
    <p>The service gmail has thrown an exception: Google.GoogleApiException:
    Google.Apis.Requests.RequestError Request payload size exceeds the
    limit: 1048576 bytes. [400] Errors [ Message[Request payload size
    exceeds the limit: 1048576 bytes.] Location[ - ] Reason[badRequest]
    Domain[global] ]</p>
  </blockquote>
  
  <p>The email itself doesn't contain anything too unique; An <code>HTML body and a 1.4 MB PDF attachment</code>. <strong>The interesting thing is that if I authorize my personal Gmail account and attempt to send the same email message  with the same attachment, everything works fine for my account. It appears that only this user is getting these errors.</strong></p>
  
  <p>Is there a best practice that I'm missing here? Or a simple solution for these errors? I've tried searching around a bit and came up with nothing. Is there a list of errors that the Gmail API return and how to handle them?</p>
  
  <p>Below is the code that we use to send the email:</p>
  
  <pre><code>public override SendEmailResponse SendEmail(string from, string to, string subject, string body,
      string cc = null, string bcc = null, MultiEntityLookup attachments = null,
      Guid? experienceId = null, List&lt;byte[]&gt; inlineImages = null, bool sansSerif = false,
      List&lt;EmailAttachment&gt; emailAttachments = null, bool isPlainTextBody = false)
  {
      // Accepted Media MIME types: message/rfc822
      MailBee.Mime.MailMessage email = new MailBee.Mime.MailMessage();
  
      email.From.Email = this.Credential.GetValueAsString("Username");
      email.From.DisplayName = this.Credential.GetLookup("UserId").Title;
      email.To = EmailUtility.ParseAndValidateEmailAddresses(to, response);
  
      if (email.To.Count == 0)
      {
          response.ErrorCode = EmailErrorCodes.NotSentInvalidTo;
          UpdateExperienceWithEmailStatus(experienceId, EmailErrorCodes.NotSentInvalidTo);
          return response;
      }
  
      if (!String.IsNullOrEmpty(cc))
      {
          email.Cc.Add(EmailUtility.ParseAndValidateEmailAddresses(cc, response));
      }
  
      if (!String.IsNullOrEmpty(bcc))
      {
          email.Bcc.Add(EmailUtility.ParseAndValidateEmailAddresses(bcc, response));
      }
  
      // Add a custom header
      if (experienceId.HasValue)
      {
          string shortExpId = EmailUtility.EncodeShortGuid(experienceId.Value);
          email.Headers.Add("X-CrelateExperienceId", shortExpId, true);
      }
  
      email.Subject = subject;
  
      if (isPlainTextBody)
      {
          email.BodyPlainText = body;
      }
      else
      {
          body = TextUtility.ConvertKendoHtmlForEmailBody(body, sansSerif);
          email.BodyHtmlText = body;
          email.MakePlainBodyFromHtmlBody();
      }
  
      // Add attachments
      if (emailAttachments != null &amp;&amp; emailAttachments.Count &gt; 0)
      {
          // If we have a array of { byte[], filename }
          foreach (EmailAttachment attach in emailAttachments)
          {
              email.Attachments.Add(attach.content, attach.fileName, String.Empty, null, null, MailBee.Mime.NewAttachmentOptions.None, MailBee.Mime.MailTransferEncoding.None);
          }
      }
      else if (attachments != null &amp;&amp; attachments.Lookups.Count &gt; 0)
      {
          // If we need to get the document from Azure
          char[] invalids = Path.GetInvalidFileNameChars();
  
          foreach (EntityLookup attachment in attachments.Lookups)
          {
              string fileName = attachment.Title;
  
              if (!String.IsNullOrEmpty(fileName))
              {
                  string safeFileName = String.Join("_", fileName.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
  
                  CloudBlockBlob contentBlob = this.Data.OrganizationBlobContainer.GetBlockBlobReference(attachment.Id.ToString("D") + "/" + fileName);
  
                  using (MemoryStream rawDoc = new MemoryStream())
                  {
                      contentBlob.DownloadToStream(rawDoc);
                      rawDoc.Seek(0, SeekOrigin.Begin);
  
                      email.Attachments.Add(rawDoc, safeFileName, String.Empty, null, null, MailBee.Mime.NewAttachmentOptions.None, MailBee.Mime.MailTransferEncoding.None);
                  }
              }
          }
      }
  
      // Attach inline images
      if (inlineImages != null &amp;&amp; inlineImages.Count &gt; 0)
      {
          var c = 0;
          foreach (byte[] image in inlineImages)
          {
              email.Attachments.Add(image, "attch" + c + ".png", "attch" + c + ".png", null, null,
                  MailBee.Mime.NewAttachmentOptions.Inline, MailBee.Mime.MailTransferEncoding.None);
              c++;
          }
      }
  
      // Create a base64 encoded string
      string encoded = null;
  
      using (MemoryStream stream = new MemoryStream())
      {
          email.SaveMessage(stream);
          stream.Seek(0, SeekOrigin.Begin);
  
          byte[] emailBytes = stream.ToArray();
  
          encoded = Convert.ToBase64String(emailBytes).TrimEnd(PADDING).Replace('+', '-').Replace('/', '_');
      }
  
      if (!String.IsNullOrEmpty(encoded))
      {
          GmailService service = new GmailService(new BaseClientService.Initializer
          {
              HttpClientInitializer = GetGoogleUserCredentialObject(),
              ApplicationName = "Our App"
          });
  
          try
          {
              Message googleMessage = new Message();
              googleMessage.Raw = encoded;
  
              string emailAddress = this.Credential.GetValueAsString("Username");
  
              // Send the email message
              Message created = service.Users.Messages.Send(googleMessage, emailAddress).Execute();
          }
          catch (Exception)
          {
              // Trace out the base64 encoded string so that we can duplicate the message
              Trace.TraceError("Failed to Send base64 encoded Google Email: " + encoded);
  
              // Save a status of error and then rethrow the original exception
              UpdateExperienceWithEmailStatus(experienceId, EmailErrorCodes.ErrorWhenSending);
              throw;
          }
      }
      else
      {
          // This is custom error code that means that the message was not sent because there was nothing to send
          response.ErrorCode = EmailErrorCodes.NotSentNoBody;
      }
  
      UpdateExperienceWithEmailStatus(experienceId, response.ErrorCode);
  
      return response;
  }
  </code></pre>