Sending a document to a distant server using a background script in Thunderbird

I am currently working on a Thunderbird extension that has the ability to upload attached files in emails. The process flow of this extension is outlined below:

  1. Clicking on the extension icon will display a popup with options to select from: "Read All", "Read Selected", and "Read Unread".
  2. Upon selecting an email with an attachment and choosing the "Read Selected" option, the listener for the "Read Selected" onclick event is activated.
  3. The onclick listener then sends a message to the background script to handle the uploading process.

Below is the code snippet I have developed so far:

popup.js

async function readSelected() {
  // This function is triggered by the listener
  const msgList = await browser.mailTabs.getSelectedMessages();
  if (msgList.messages) {
     await browser.runtime.sendMessage({
        caller: 'readSelected',
        messages: msgList.messages
     });
  }
}

background.js

browser.runtime.onMessage.addListener((req, sender, res) => {
  // 'messages' is an Array of MessageHeader objects
  const { caller, accounts, all, messages } = req;
  // ... Other code for handling different scenarios
  console.log('Reading selected');
  console.log(messages);
  const ids = [];
  for (const msg of messages) {
      ids.push(msg.id);
  }
  // Maps all IDs to promises that resolve to MessagePart objects
  Promise.all(ids.map(id => browser.messages.getFull(id)))
    .then(messages => {
        console.log(messages);
    }).catch(e => console.error(e));
});

While monitoring the console in background.js, I noticed that each MessagePart object contains a nested array called parts, which also consists of more MessagePart objects. Within these objects, I can see the names of the attachments (such as a DOCX file in my case). However, the question arises - how do I access the actual attachment file? I require the binary file data in order to convert it into a Base64 string before proceeding with the upload to the server. I reviewed similar questions on Stack Overflow such as post1 and post2, but I remain uncertain about using the nsIFile interface since it necessitates a URI, which is not provided for the parts.

If additional information is required, please feel free to ask in the comments section and I will update the query accordingly (the remaining code primarily handles calls for the other options mentioned in point (1) above). Any guidance or assistance would be greatly appreciated. Thank you.

Answer №1

It doesn't appear feasible at the moment. However, you do have the option of using messages.getRaw() to retrieve the complete message source in a promise, along with any attachments. The downside is that you would then need to parse the message again, which can be quite challenging.

I recommend keeping an eye on and possibly commenting on relevant Thunderbird bug reports. I came across this one and maybe that one that could be related to your issue.

Please note that the other questions you referenced pertain to older types of add-ons that are not based on the WebExtensions API. While using legacy components is not advised for modern add-ons (due to the risk of them breaking during upgrades), it might still be possible to access these legacy APIs through experimental features known as experiments. However, I don't have enough experience with them to confirm if they would help you achieve your goals.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with height in self-invoking function not functioning correctly

Issue with height not functioning correctly inside self-invoking function, but works fine within (document).ready(function() (function($){ var clientHeight = document.getElementById('home').clientHeight; alert(clientHeight); })(jQuery); <di ...

Retrieve the node-postgres result and store it in a separate object beyond the callback function

Currently, I am in the process of converting a data profiling script originally written in Python to JavaScript while following the Wes Bos beginner Javascript Course. This script is designed to take database connection details and a specified target tabl ...

Merging data sets with Javascript: A comprehensive guide

As a newcomer to the world of javscript, I'm faced with what seems like a simple question. I'm working with two datasets that contain a common column and I'd like to merge them together. The structure of the datasets is as follows: const da ...

Error encountered when attempting to retrieve HTML content from localhost using AJAX

Attempting to insert HTML code into a div element using ajax, similar to how it's done with an iframe. Testing this out locally first to avoid Same Origin Policy complications. The web application is currently hosted on a wamp server. There are two ...

Apply a specific class using JavaScript/jQuery when a user selects a specific timezone from the user interface

Currently, I am coding in HTML with the code below extracted from this website link. The listings under timezone ET are all correct as they align with the accurate dates; however, for other timezones (PT, MT, CT, AT, NT) some shows seem to be on incorrect ...

The second request made with $.ajax is bypassed

I have been working on integrating the Google Maps JavaScript API and attempting to update a heat map when a user clicks on a specific div element. The latitude and longitude data used for the heatmap are fetched from local JSON files. While I have success ...

It seems like my ajax function is functioning properly, but the data is not getting submitted

Having trouble sending the value of my selector to a PHP file through AJAX. The success function is working, and when I directly visit "your_php_script.php" it functions as expected. However, why is the PHP page not showing up on the page with the AJAX r ...

When I close all of my tabs or the browser, I aim to clear the local storage

Could you recommend any strategies for clearing local storage upon closing the last tab or browser? I have attempted to use local storage and session storage to keep track of open and closed sessions in an array stored in local storage. However, this meth ...

"if the condition is not met, the outcome will not be shown in the while

I have a looping structure that includes conditions for if, else if, and else. However, I have noticed that the else condition at the end of the loop is not being executed as expected. I am currently investigating why this might be happening. Here is the ...

How can you create an event that is focused on options using Material-UI's Autocomplete feature?

This is regarding Material-UI's Autocomplete feature. I am looking for a way to track which autocomplete choice the user is currently focused on, whether it be through hovering over with the mouse or using keyboard arrows - before any actual selection ...

Using Javascript and Regular Expressions to separate and preserve the delimiter

I'm facing an issue with my regex that splits a string into arrays. Everything is working smoothly except for the fact that I want to retain part of the delimiter. This is the regex I am using: (&#?[a-zA-Z0-9]+;)[\s] In my JavaScript cod ...

There is an issue with the syntax in your for-loop control where a closing parenthesis is missing

When I try to navigate through the arrays from 1 to 4 in the given JSON data, Firebug shows me an error message: SyntaxError: missing ) after for-loop control [Break On This Error] for( x in LGIntake.corpCodeOptions.marketSegment.1){ StartI...aseId=0 ...

Shifting an item to a specific location using three.js

I'm attempting to fire bullets or projectiles utilizing three.js: let renderer, camera, scene, light, plane, cube, spheres; initialize(); animate(); function initialize() { renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }); ...

Hide elements forever once the form is submitted

I'm seeking help to figure out how to make certain elements disappear after a form submission on my website's dashboard page. Specifically, I need to hide three elements once the user has submitted a form. Elements that need to be hidden: .vc_t ...

Implement Acrobat JavaScript to enforce a mandatory separate field when a checkbox is selected

As a designer with limited coding skills, I have developed an acrobat form that includes several due date fields. These fields are only mandatory if a specific checkbox is selected. I am looking for the javascript code that will validate the requirement: ...

Challenges encountered with autofill and a null string

When I try to fetch data from the server for autocomplete, it returns no options even though two options are displayed in the console after making an API call. The value I enter includes two empty spaces followed by 'IPH', triggering the API call ...

Is there a way to retrieve the current state of a Material UI component in a React functional component without needing to trigger an event by clicking on

Seeking a way to retrieve current values of Material Ui components without the need to click on any event after page reloads or DOM changes. These values are pulled from a database. My goal is to confirm whether the values have been updated or not by chec ...

What is the importance of utilizing `document.createElementNS` when incorporating `svg` elements into an HTML webpage using JavaScript?

Not Working Example: const svg = document.createElement('svg') svg.setAttribute('height', '100') svg.setAttribute('width', '100') document.body.appendChild(svg) const rect = document.createElement(&apos ...

Display temporary image until real image loads within ng-repeat angularjs

I am looking to display a placeholder image while the actual image is being loaded. I have tried using the ng-image-appear plugin. The issue I'm facing is that the placeholder image does not appear for img elements inside ng-repeat, although it works ...

Drawing images on a Canvas using specified coordinates: A step-by-step guide

https://i.stack.imgur.com/YkibI.jpg I've been trying to position images on specific coordinates, but I'm having trouble getting the shapes and angles right. Currently, only the top left corner is matching correctly. var _width, _height; var im ...