使用.NET客户端库的SendEmail上的Gmail API错误

时间:2016-10-19 06:55:56

标签: c# .net google-api gmail google-api-dotnet-client

我们的网络应用程序使用Google .Net客户端库为我们的用户发送电子邮件。一位特定用户在发送电子邮件时遇到问题;主要是附件。我们似乎得到的2条错误消息如下:

  

服务gmail引发了异常:Google.GoogleApiException:   Google.Apis.Requests.RequestError'raw'RFC822有效内容消息字符串   或通过/ upload / *上传消息需要[400]错误[   消息['raw'RFC822有效负载消息字符串或通过上传消息   / upload / *需要网址]位置[ - ]原因[badRequest]   域[全球]]

最近:

  

服务gmail引发了异常:Google.GoogleApiException:   Google.Apis.Requests.RequestError请求有效负载大小超过   限制:1048576字节。 [400]错误[消息[请求有效负载大小   超过限制:1048576字节。]位置[ - ]原因[badRequest]   域[全球]]

电子邮件本身并不包含任何太独特的内容;一个HTML body and a 1.4 MB PDF attachment有趣的是,如果我授权我的个人Gmail帐户并尝试使用相同的附件发送相同的电子邮件,那么我的帐户一切正常。似乎只有这个用户才会收到这些错误。

我在这里缺少最佳做法吗?或者这些错误的简单解决方案?我尝试了一下,并没有想到什么。是否有Gmail API返回的错误列表以及如何处理这些错误?

以下是我们用来发送电子邮件的代码:

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<byte[]> inlineImages = null, bool sansSerif = false,
    List<EmailAttachment> 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 && emailAttachments.Count > 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 && attachments.Lookups.Count > 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 && inlineImages.Count > 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;
}

0 个答案:

没有答案