Send files from Dolphin to Thunderbird with a click

A small Python script + a .desktop file let you select one or more files/folders in Dolphin, click “Send by email”, and immediately open a Thunderbird compose window with the attachments already prepared.

Why it’s useful

  • Time-saving: no copying into a temporary folder, no manual compression.
  • Full control: Thunderbird opens in draft/compose mode; you write the recipient, subject, and body, then hit Send yourself.
  • Smart rules:
    • Up to 5 files → individual attachments.
    • More than 5 files or at least one folder → a single selected.zip archive containing everything.
    • Paths inside the archive are relative, not absolute, so the zip file is “clean” and works anywhere.

Prerequisites

  • KDE Plasma desktop with Dolphin.
  • Thunderbird installed and available in PATH.
  • The zip utility (usually already installed).
  • Python 3 (the helper script is written in Python).

Installation

1. The helper script

Copy the following script into an executable directory for your user, such as ~/.local/bin/dolphin_thunderbird_send.py, and adjust the mailer variable if needed:

#!/usr/bin/env python3
"""
Dolphin service menu helper: prepares attachments from the selected items
and opens a Betterbird compose window (no automatic sending).

Usage:
    dolphin_thunderbird_send.py <selected-path-1> [selected-path-2 ...]

Packaging rules:
    * If any selected item is a directory, or more than 5 files are selected,
      all items are bundled into a single ZIP archive and attached once.
    * Otherwise each selected file is attached individually.
"""

import os
import subprocess
import sys
import shutil
import tempfile
from pathlib import Path
from urllib.parse import unquote, urlparse

mailer = "betterbird"

def main() -> int:
    # KDE passes the selected URLs/paths as the remaining arguments.
    selected_paths: list[Path] = []
    for arg in sys.argv[1:]:
        arg = arg.strip()
        if not arg:
            continue
        if arg.startswith("file:"):
            parsed = urlparse(arg)
            selected_paths.append(Path(unquote(parsed.path)))
        else:
            selected_paths.append(Path(arg))
    if not selected_paths:
        return 0
    selected = [p.expanduser().resolve() for p in selected_paths]

    has_dir = any(p.is_dir() for p in selected)
    file_count = sum(1 for p in selected if p.is_file())

    attachments: list[str] = []
    tmpdir: Path | None = None

    if has_dir or file_count > 5:
        # Bundle everything into a single ZIP archive, storing only
        # relative paths (no absolute paths) inside the archive.
        tmpdir = Path(tempfile.mkdtemp(prefix="dolphin-thunderbird-"))
        zip_path = tmpdir / "selected.zip"

        # Prepare a flat temp directory with only the item names (no full paths).
        for p in selected:
            if p.is_file():
                # Copy the file using only its basename; if a file with the same name
                # already exists, add a numerical suffix to avoid overwriting.
                dest = tmpdir / p.name
                counter = 1
                while dest.exists():
                    stem, ext = p.stem, p.suffix
                    dest = tmpdir / f"{stem}_{counter}{ext}"
                    counter += 1
                shutil.copy2(p, dest)
            elif p.is_dir():
                # Copy the whole directory tree under the directory's basename.
                dest_dir = tmpdir / p.name
                if dest_dir.exists():
                    shutil.rmtree(dest_dir)
                shutil.copytree(p, dest_dir)

        # Create the ZIP from inside the temp directory so that only the
        # prepared relative paths are stored.
        subprocess.run(["zip", "-r", str(zip_path), "."], cwd=tmpdir, check=True)
        attachments = [str(zip_path)]
    else:
        # Attach each file individually (no zip).
        attachments = [str(p) for p in selected if p.is_file()]

    joined_att = ','.join(attachments)
    attach_arg = f"'{joined_att}'"

    subject = "Files from Dolphin"
    body = "Attachments prepared from Dolphin selection."
    compose_str = (
        f"subject={subject},"
        f"body={body},"
        f"attachment={attach_arg}"
    )

    try:
        subprocess.run([mailer, "-compose", compose_str], check=True)
    except FileNotFoundError:
        print(f"{mailer} not found in PATH", file=sys.stderr)
        return 1
    except subprocess.CalledProcessError as exc:
        print(f"{mailer} exited with code {exc.returncode}", file=sys.stderr)
        return exc.returncode

    return 0

if __name__ == "__main__":
    sys.exit(main())

Make it executable:

chmod +x ~/.local/bin/dolphin_thunderbird_send.py

2. The KDE service menu

Create (or overwrite) the file:

~/.local/share/kio/servicemenus/dolphin-thunderbird-send.desktop

with this content:

[Desktop Entry]
Type=Service
MimeType=inode/directory;application/octet-stream;
Actions=sendByEmail

[Desktop Action sendByEmail]
Name=Send by email
Name[it]=Invia per email
Icon=mail-send
Exec=/home/yourusername/.local/bin/dolphin_thunderbird_send.py %U

Replace /home/yourusername/ with the path to your home directory. Save the file: Dolphin will automatically pick up the new action; no need to restart Plasma.

How to use it

  1. Open Dolphin.
  2. Select one or more files, a folder, or a mix of both.
  3. Right-click the selection.
  4. Choose Send by email (or Invia per email, depending on your system language).
  5. Thunderbird opens with a new compose window; the attachments are already added.
  6. Fill in To, Subject, and Body, then click Send.

How the script works

The script receives the items selected in Dolphin via command-line arguments (sys.argv[1:]), because the .desktop file uses the %U placeholder.

The bundling logic works as follows:

  • Check:
    • If there is at least one directory or more than 5 files → a ZIP is needed.
    • Otherwise → individual attachments.
  • Creating the ZIP (when needed):
    • Each item is copied into a temporary directory using only its base name (no absolute path).
    • If two items have the same name, a numeric suffix is added (file_1.txt).
    • zip -r selected.zip . runs inside that temporary directory, so the archive contains relative paths (file.txt, docs/, …) rather than /home/user/....
  • Launching Thunderbird:
    • A compose_str string is built like subject=Files from Dolphin,body=...,attachment=selected.zip.
    • thunderbird -compose "..." is executed, opening the compose window with the attachments already in place.

Behavior table

Selection in DolphinWhat happens
Up to 5 files, no foldersEach file attached individually
More than 5 files, no foldersSingle selected.zip archive with all files (relative names)
A folder is selected (even with few files)Single selected.zip archive containing the folder and all files inside it
No items selectedNo window is opened (script exits immediately)

Conclusion

With a few simple steps, you can turn Dolphin into a smart “send by email button” capable of creating clean ZIPs (without absolute paths) and leaving Thunderbird with just the job of composing the message. It is a lightweight solution, with no unusual dependencies, and designed specifically for the KDE environment.

Leave a Reply