Error sending big attachments : Invalid total bytes specified in the Content-Range header

Horacio Crespo 20 Reputation points
2023-02-01T20:19:51.85+00:00

Hello everyone,

I'm trying to send large attachments, the attachments <=3MB work fine, but for the big attachments some times it doesn't works and the error is: "Invalid total bytes specified in the Content-Range header". What could be the problem ?



try
                {
                    Message draft = await graphClient
                        .Users[sender]
                        .MailFolders
                        .Drafts
                        .Messages
                        .Request()
                        .AddAsync(message);


                    if (e.GetAttributeValue<int>("attachmentcount") >= 1)
                    {
                        var attachmentColl = crmManager.RetrievePendingAttachments(e.ToEntityReference());

                        foreach (var a in attachmentColl.Entities)
                        {
                            string body = a.GetAttributeValue<string>("body");
                            string oDataType = "#microsoft.graph.fileAttachment";
                            byte[] contentBytes = Convert.FromBase64String(body);
                            string contentType = a.GetAttributeValue<string>("mimetype");
                            string contentId = a.GetAttributeValue<string>("filename");
                            string fileName = a.GetAttributeValue<string>("filename");
                            int fileSize = a.GetAttributeValue<int>("filesize");


                            double fileSizeMegabyes = (fileSize / 1024f) / 1024f;

                            if (fileSizeMegabyes <= 3) //attachment <= 3MB
                            {
                                var fileAttachment = new FileAttachment
                                {
                                    ODataType = oDataType,
                                    ContentBytes = contentBytes,
                                    ContentType = contentType,
                                    ContentId = contentId,
                                    Name = fileName
                                };

                                await graphClient
                                    .Users[sender]
                                    .Messages[draft.Id]
                                    .Attachments
                                    .Request()
                                    .AddAsync(fileAttachment);
                            }
                            else //attachment > 3MB
                            {
                                var attachmentItem = new AttachmentItem
                                {
                                    AttachmentType = AttachmentType.File,
                                    Name = fileName,
                                    Size = fileSize,
                                    ContentType = contentType,
                                };

                                var uploadSession = await graphClient
                                    .Users[sender]
                                    .Messages[draft.Id]
                                    .Attachments
                                    .CreateUploadSession(attachmentItem)
                                    .Request()
                                    .PostAsync();

                                var stream = new MemoryStream(contentBytes);
                                var maxSliceSize = 320 * 1024;
                                var fileUploadTask = new LargeFileUploadTask<FileAttachment>(uploadSession, stream, maxSliceSize);

                                IProgress<long> progressCallback = new Progress<long>(prog =>
                                {
                                    Program._logger.Info($"Uploaded {prog} bytes of {contentBytes.Length} bytes");
                                });

                                try
                                {
                                    var uploadResult = await fileUploadTask.UploadAsync(progressCallback);

                                    if (!uploadResult.UploadSucceeded)
                                        Program._logger.Error($"Error uploading the big attachment: {fileName}  ");

                                }
                                catch (ServiceException ex)
                                {
                                    Program._logger.Error($"Error: {ex.Error.Message}");
                                }
                            }
                        }

                        result = await graphClient
                                   .Users[sender]
                                   .Messages[draft.Id]
                                   .Send()
                                   .Request()
                                   .WithMaxRetry(5)
                                   .PostResponseAsync();
                    }

                    if (result != null & (result.StatusCode == HttpStatusCode.OK || result.StatusCode == HttpStatusCode.Accepted))
                    {
                        Program._logger.Info($"Response: {result.StatusCode} - {result.Content}");
                        Program._logger.Info($"Changing email status to Completed - Sent");
                        crmManager.ChangeEmailStatus(crmEmailId, 1, 3);
                    }
                    else if (result != null)
                    {
                        Program._logger.Error($"Response: {result.StatusCode} - {result.Content}");
                        Program._logger.Info($"Changing email status to Open - Failed");
                        crmManager.ChangeEmailStatus(crmEmailId, 0, 8);
                    }
                }
                catch (ServiceException ex)
                {
                    error = ex.InnerException != null ? ex.InnerException.Message : ex.Error.Message;
                    Program._logger.Error($" An error ocurred: {error}");
                }

enter image description here

This is the log that pass for the same part of code and send the file without problems.

User's image

This is the log when there is the error, the email was send but without the attachment

I uploaded the PDF file here: https://easyupload.io/r0wxqz

This is the debug variables for the pdf that isn't working, before the line

var fileUploadTask = new LargeFileUploadTask<FileAttachment>(uploadSession, stream, maxSliceSize);

Can be maybe the value of stream.length with value 3976877 and the attachmentItem.Size with value 3976878 ?

User's image

Anybody had the same problem?

Thanks in advance

Horacio

Microsoft Security | Microsoft Graph
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bhanu Kiran 3,616 Reputation points
    2023-03-02T23:33:26.0833333+00:00

    Hi @Horacio Crespo ,

    Hope you are doing well.

    From the error message it seems that the total bytes specified in the content-Range header is invalid.

    The Content-Range header has the following format:

    Content-Range: bytes <startindex>-<endindex>/<totallength>
    

    Your issue appears to be a mixing of indexes (0-based) and lengths (1-based). For a 100-byte file your header would need to look like:

    Content-Range: bytes 0-99/100
    

    Please check and validate if this issue still exists.

    Hope this helps.

    If the answer is helpful, please click Accept Answer and kindly upvote. If you have any further questions about this answer, please click Comment.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.