Sending Faxes with Asterisk on Ubuntu: Permissions, ImageMagick, and Other Stumbling Blocks

November 30, 2026

Faxing in 2026? Honestly, nobody needs that anymore. Still, I used Python and Asterisk to build a small interface that sends a PDF as a fax with a mouse click. Along the way, I learned more about Linux permissions, ImageMagick, IAX2, and Asterisk than in any other project this year. Here are step-by-step instructions, including all the stumbling blocks, and with the help of the AI Claude, without whom I would probably still be reading log files today.

The preliminary work is described at https://elektronikbasteln.pl7.de/pdf-dateien-als-faxe-mit-asterisk-versenden. You should start there. That method still works without a graphical interface and therefore does not need a Python program.

Make backup copies of the files before changing the Asterisk configuration!

Bildschirmfoto zu 2026 11 30 14 52
A Python script with Tkinter provides the graphical user interface.

The Python script:

#!/usr/bin/env python3
"""Fax-GUI für Asterisk (Tkinter)

Ablauf:
  1. PDF wird als a.pdf in den Ausgangsordner kopiert (so erwartet es
     der Dialplan aus dem Blogartikel).
  2. Über die Asterisk-Konsole wird ein Anruf "wie von einem Telefon"
     gestartet: Local/<Vorwahl><Nummer>@<Kontext>
     Die vorhandene extensions.conf (Konvertierung PDF->TIFF, Macro
     faxversand) wird also unverändert benutzt.
  3. Der Fortschritt wird im Statusfenster angezeigt. Dafür hängt sich das
     Programm einmal mit "asterisk -rnvvv" an die Konsole und liest mit.
     Während der Übertragung werden keine weiteren asterisk-Prozesse
     gestartet (Faxe sind empfindlich gegen Zeitschwankungen).

Optional: "pip install tkinterdnd2" aktiviert Drag & Drop.
"""
import json
import os
import pty
import re
import shutil
import subprocess
import threading
import time
import tkinter as tk
from datetime import datetime
from pathlib import Path
from tkinter import filedialog, messagebox, ttk

try:
    from tkinterdnd2 import DND_FILES, TkinterDnD
    BaseTk = TkinterDnD.Tk
    HAS_DND = True
except Exception:
    BaseTk = tk.Tk
    HAS_DND = False

CONFIG_FILE = Path.home() / ".config" / "fax-gui.json"
DEFAULTS = {
    "pdf_dir": str(Path.home()),
    "outgoing_dir": "/var/spool/asterisk/fax/outgoing",
    "extensions_conf": "/etc/asterisk/extensions.conf",
    "asterisk_cmd": "asterisk",
    "context": "telefone",
    "prefix": "1094",
    "history": [],
}

# Ergebniszeilen aus dem Macro faxversand (NoOp-Ausgaben)
NOOP_RE = re.compile(r'NoOp\("[^"]*", "(STATUS|PAGES|RATE|ERROR): ?([^"]*)"')
ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")


def read_lines(fd):
    """Liefert Zeilen aus einem Dateideskriptor (Pseudo-Terminal)."""
    buf = b""
    while True:
        try:
            chunk = os.read(fd, 4096)
        except OSError:
            return
        if not chunk:
            return
        buf += chunk
        while b"\n" in buf:
            line, buf = buf.split(b"\n", 1)
            yield ANSI_RE.sub("", line.decode("utf-8", "replace")).strip()


def load_cfg():
    cfg = dict(DEFAULTS)
    try:
        cfg.update(json.loads(CONFIG_FILE.read_text()))
    except (OSError, ValueError):
        pass
    return cfg


def save_cfg(cfg):
    try:
        CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
        CONFIG_FILE.write_text(json.dumps(cfg, indent=2))
    except OSError:
        pass


def find_routes(path):
    """Sucht in der extensions.conf Wahlregeln, die das Macro faxversand
    aufrufen. Liefert Liste von (Kontext, Vorwahl)."""
    routes = []
    try:
        text = Path(path).read_text(errors="replace")
    except OSError:
        return routes
    ctx = cur = None
    for line in text.splitlines():
        s = line.strip()
        if s.startswith(";"):
            continue
        m = re.match(r"\[([^\]]+)\]", s)
        if m:
            ctx, cur = m.group(1), None
            continue
        m = re.match(r"exten\s*=>\s*_?(\d+)", s)
        if m:
            cur = m.group(1)
            continue
        if "M(faxversand" in s and ctx and cur:
            if (ctx, cur) not in routes:
                routes.append((ctx, cur))
            cur = None
    return routes


class FaxApp(BaseTk):
    def __init__(self):
        super().__init__()
        self.title("Fax senden")
        self.minsize(600, 600)
        self.cfg = load_cfg()
        self.files = {}
        self.routes = []
        self.busy = False
        self.build()
        self.refresh_files()
        self.refresh_routes()

    # ---------------------------------------------------------------- GUI
    def build(self):
        style = ttk.Style(self)
        try:
            style.theme_use("clam")
        except tk.TclError:
            pass
        style.configure("TLabel", font=("Sans", 11))
        style.configure("Big.TButton", font=("Sans", 15, "bold"), padding=12)

        frm = ttk.Frame(self, padding=16)
        frm.pack(fill="both", expand=True)
        frm.columnconfigure(1, weight=1)
        pad = dict(padx=6, pady=8)

        ttk.Label(frm, text="Empfängernummer:").grid(row=0, column=0, sticky="w", **pad)
        self.num = ttk.Combobox(frm, font=("Sans", 15), values=self.cfg["history"])
        self.num.grid(row=0, column=1, columnspan=2, sticky="ew", **pad)
        self.num.focus_set()

        ttk.Label(frm, text="PDF-Datei:").grid(row=1, column=0, sticky="w", **pad)
        self.pdf = ttk.Combobox(frm, state="readonly", font=("Sans", 11))
        self.pdf.grid(row=1, column=1, sticky="ew", **pad)
        ttk.Button(frm, text="Durchsuchen…", command=self.browse).grid(row=1, column=2, **pad)

        hint = "Ordner: " + self.cfg["pdf_dir"]
        if HAS_DND:
            hint += "   (PDF kann auch hineingezogen werden)"
        self.hint = ttk.Label(frm, text=hint, foreground="#666")
        self.hint.grid(row=2, column=1, columnspan=2, sticky="w", padx=6)

        box = ttk.LabelFrame(frm, text="Asterisk-Einstellungen", padding=8)
        box.grid(row=3, column=0, columnspan=3, sticky="ew", pady=12)
        box.columnconfigure(1, weight=1)
        ttk.Label(box, text="Route:").grid(row=0, column=0, sticky="w")
        self.route = ttk.Combobox(box, state="readonly")
        self.route.grid(row=0, column=1, columnspan=3, sticky="ew", padx=6, pady=3)
        self.route.bind("<<ComboboxSelected>>", self.on_route)
        ttk.Label(box, text="Vorwahl:").grid(row=1, column=0, sticky="w")
        self.prefix = ttk.Entry(box, width=14)
        self.prefix.insert(0, self.cfg["prefix"])
        self.prefix.grid(row=1, column=1, sticky="w", padx=6, pady=3)
        ttk.Label(box, text="Kontext:").grid(row=1, column=2, sticky="e")
        self.context = ttk.Entry(box, width=18)
        self.context.insert(0, self.cfg["context"])
        self.context.grid(row=1, column=3, sticky="w", padx=6, pady=3)

        self.send_btn = ttk.Button(frm, text="Fax senden", style="Big.TButton",
                                   command=self.send)
        self.send_btn.grid(row=4, column=0, columnspan=3, sticky="ew", pady=8)

        ttk.Label(frm, text="Status:").grid(row=5, column=0, sticky="w", padx=6)
        self.log_box = tk.Text(frm, height=12, state="disabled", wrap="word",
                               font=("Monospace", 10), bg="#fafafa")
        self.log_box.grid(row=6, column=0, columnspan=3, sticky="nsew", padx=6, pady=4)
        frm.rowconfigure(6, weight=1)

        if HAS_DND:
            self.drop_target_register(DND_FILES)
            self.dnd_bind("<<Drop>>", self.on_drop)
        self.bind("<Return>", lambda e: self.send())

    def log(self, msg):
        def _do():
            self.log_box.configure(state="normal")
            self.log_box.insert("end", f"{datetime.now():%H:%M:%S}  {msg}\n")
            self.log_box.see("end")
            self.log_box.configure(state="disabled")
        self.after(0, _do)

    # ------------------------------------------------------- Dateien/Routen
    def refresh_files(self, select=None):
        folder = Path(self.cfg["pdf_dir"])
        try:
            pdfs = sorted(folder.glob("*.pdf"), key=lambda p: p.stat().st_mtime,
                          reverse=True)
        except OSError:
            pdfs = []
        for p in list(self.files.values()):  # frühere Einzelauswahlen behalten
            if p not in pdfs and p.exists():
                pdfs.append(p)
        self.files = {p.name: p for p in pdfs}
        self.pdf["values"] = list(self.files)
        if select and select.name in self.files:
            self.pdf.set(select.name)
        elif self.files and not self.pdf.get():
            self.pdf.current(0)

    def browse(self):
        name = filedialog.askopenfilename(
            title="PDF auswählen", initialdir=self.cfg["pdf_dir"],
            filetypes=[("PDF-Dateien", "*.pdf"), ("Alle Dateien", "*.*")])
        if name:
            self.add_file(Path(name))

    def add_file(self, path):
        if path.suffix.lower() != ".pdf":
            messagebox.showwarning("Fax", "Bitte eine PDF-Datei wählen.")
            return
        self.cfg["pdf_dir"] = str(path.parent)
        self.hint.configure(text="Ordner: " + self.cfg["pdf_dir"])
        self.files[path.name] = path
        self.refresh_files(select=path)

    def on_drop(self, event):
        for name in self.tk.splitlist(event.data):
            self.add_file(Path(name))
            break

    def refresh_routes(self):
        self.routes = find_routes(self.cfg["extensions_conf"])
        labels = [f"{pre}  (Kontext {ctx})" for ctx, pre in self.routes]
        self.route["values"] = labels
        if labels:
            self.route.current(0)
            self.on_route()
        else:
            self.route.set("extensions.conf nicht lesbar – Vorwahl/Kontext von Hand eintragen")

    def on_route(self, _event=None):
        i = self.route.current()
        if 0 <= i < len(self.routes):
            ctx, pre = self.routes[i]
            self.context.delete(0, "end"); self.context.insert(0, ctx)
            self.prefix.delete(0, "end"); self.prefix.insert(0, pre)

    # -------------------------------------------------------------- Senden
    def send(self):
        if self.busy:
            return
        number = re.sub(r"[\s\-/()]", "", self.num.get())
        if not re.fullmatch(r"\+?\d+", number):
            messagebox.showwarning("Fax", "Bitte eine gültige Empfängernummer eingeben.")
            return
        number = number.lstrip("+")
        name = self.pdf.get()
        if name not in self.files:
            messagebox.showwarning("Fax", "Bitte eine PDF-Datei auswählen.")
            return
        pdf = self.files[name]
        prefix = self.prefix.get().strip()
        ctx = self.context.get().strip()
        if not ctx:
            messagebox.showwarning("Fax", "Kontext fehlt.")
            return
        if not messagebox.askyesno("Fax senden", f"„{name}“ an {number} faxen?"):
            return
        # Einstellungen merken
        hist = [number] + [h for h in self.cfg["history"] if h != number]
        self.cfg.update(history=hist[:15], prefix=prefix, context=ctx)
        save_cfg(self.cfg)
        self.num["values"] = self.cfg["history"]
        self.busy = True
        self.send_btn.configure(state="disabled")
        threading.Thread(target=self.worker, args=(pdf, prefix, number, ctx),
                         daemon=True).start()

    def ast(self, command):
        r = subprocess.run([self.cfg["asterisk_cmd"], "-rx", command],
                           capture_output=True, text=True, timeout=20)
        return (r.stdout + r.stderr).strip()

    def worker(self, pdf, prefix, number, ctx):
        con = timer = master = None
        try:
            out_dir = Path(self.cfg["outgoing_dir"])
            self.log(f"Kopiere {pdf.name} nach {out_dir}/a.pdf …")
            shutil.copyfile(pdf, out_dir / "a.pdf")
            try:
                (out_dir / "a.tif").unlink()
            except OSError:
                pass

            # Eine einzige dauerhafte Konsolenverbindung zum Mitlesen
            # Pseudo-Terminal, sonst puffert asterisk die Ausgabe bei einer Pipe
            master, slave = pty.openpty()
            con = subprocess.Popen(
                [self.cfg["asterisk_cmd"], "-rnvvv"],
                stdin=slave, stdout=slave, stderr=slave, close_fds=True)
            os.close(slave)
            timer = threading.Timer(900, con.terminate)
            timer.start()
            time.sleep(1.5)

            target = f"Local/{prefix}{number}@{ctx}"
            self.log(f"Starte Anruf {target} …")
            res = self.ast(f"channel originate {target} application Wait 900")
            if "rror" in res or "nable" in res or "No such" in res:
                self.log("Asterisk meldet: " + res)
                return
            self.log("PDF wird in TIFF umgewandelt, Verbindung wird aufgebaut …")
            self.follow(master, prefix + number)
        except subprocess.TimeoutExpired:
            self.log("Fehler: Asterisk-Konsole antwortet nicht.")
        except (OSError, subprocess.SubprocessError) as exc:
            self.log(f"Fehler: {exc}")
        finally:
            if timer:
                timer.cancel()
            if con:
                con.terminate()
            if master is not None:
                try:
                    os.close(master)
                except OSError:
                    pass
            self.busy = False
            self.after(0, lambda: self.send_btn.configure(state="normal"))

    def follow(self, fd, key):
        """Liest die Konsolenausgabe mit und meldet den Fortschritt."""
        found, called, sending = {}, False, False
        for line in read_lines(fd):
            if not line:
                continue
            if "WARNING[" in line or "ERROR[" in line:
                self.log("Asterisk: " + line[:200])
            if not called and "Called " in line and "Local/" not in line:
                called = True
                self.log("Empfänger wird angerufen …")
            if not sending and "Executing" in line and "SendFAX" in line:
                sending = True
                self.log("Fax wird übertragen …")
            m = NOOP_RE.search(line)
            if m:
                found[m.group(1)] = m.group(2).strip()
            if f"Spawn extension (telefone, {key}" in line and "exited" in line:
                break
        else:
            self.log("Zeitüberschreitung oder Verbindung zur Konsole verloren – "
                     "bitte in der Asterisk-Konsole nachsehen.")
            return
        status = found.get("STATUS")
        if status == "SUCCESS":
            self.log(f"✔ Fax erfolgreich gesendet – {found.get('PAGES', '?')} Seite(n), "
                     f"{found.get('RATE', '?')} bit/s")
        elif status:
            self.log(f"✘ Fax fehlgeschlagen: {status} {found.get('ERROR', '')}")
        elif sending:
            self.log("✘ Übertragung abgebrochen (kein Faxergebnis).")
        else:
            self.log("✘ Empfänger nicht erreicht (besetzt, nicht erreichbar oder "
                     "Kanaltyp fehlt) – siehe Asterisk-Meldung oben.")


if __name__ == "__main__":
    FaxApp().mainloop()

 

The starting point: On my desktop computer, a roughly ten-year-old Fujitsu Esprimo running Ubuntu MATE 24.04, I run my own Asterisk 20. It has only one job: sending faxes. It is connected over an IAX2 link to the Asterisk on my Raspberry Pi. The Raspberry Pi is my actual phone system and sets up the connections to the internal and external extensions. These include a Brother fax machine on my home network, a FritzBox in the house, and a FritzBox in Germany that registers with the Raspberry Pi over the internet as a SIP number. So the Esprimo does not dial into the phone network itself. It sends the fax over IAX2 to the Raspberry Pi, which then connects to the destination. I described how the dial rules and the macro for sending faxes are built in the dialplan in my earlier article about sending faxes with Asterisk. This article covers everything around it that is needed to make the whole thing work conveniently from a graphical interface.

What is in the extensions.conf: This is for the Asterisk on my Ubuntu MATE desktop computer. Here is the relevant excerpt:

;===============================================================================
; extensions.conf - Einfacher Dialplan für 3000-3999
;===============================================================================

[general]
static=yes
writeprotect=no


;-------------------------------------------------------------------------------
; Kontext: telefone
;-------------------------------------------------------------------------------
[telefone]

;  Faxversand. 1094 als Vorwahl und dann direkt danach
;  als Durchwahl die Faxnummer des Empfängers wählen
;  Das Programm ImageMagick für die Konvertierung von PDF nach TIFF muss
;  installiert und konfiguriert sein. Erklärung im Text dieses Artikels

; Fall A

; Faxversand 1094 für zu internen SIP-Accounts
exten => _1094X.,1,Noop(Faxversand von Asterisk von "${CALLERID(name)}" <${CALLERID(num)}>)
 same => n,Noop(Als Durchwahl Vorwahl 1094 + SIP-Nummer des Ziels wählen)
 same => n,Noop(nur an interne SIP-Accounts möglich)
 same => n,Playback(hello)
 same => n,Wait(1)
 same => n,Playback(vm-dialout)
 same => n,System(convert -density 204x196 -depth 2 -monochrome -resize 1728x -units PixelsPerInch /var/spool/asterisk/fax/outgoing/a.pdf -compress Fax /var/spool/asterisk/fax/outgoing/a.tif)
 same => n,Set(SIP_CODEC=alaw)
 same => n,Playback(vm-dialout)
 same => n,Dial(SIP/${EXTEN:4},,M(faxversand))
 same => n,Hangup()

; Fall B
 
; Faxversand 1094 + 8835 zu einem anderen Server via Asterisk
exten => _10948835X.,1,Noop(Faxversand von Asterisk von "${CALLERID(name)}" <${CALLERID(num)}>)
 same => n,Noop(Als Durchwahl Vorwahl 1094 + 8835 + Nummer des Ziels auf dem anderen Server)
 same => n,Noop(nur zu Nummern auf Volkers Raspi möglich)
 same => n,Playback(hello)
 same => n,Wait(1)
 same => n,Playback(vm-dialout)
 same => n,System(convert -density 204x196 -depth 2 -monochrome -resize 1728x -units PixelsPerInch /var/spool/asterisk/fax/outgoing/a.pdf -compress Fax /var/spool/asterisk/fax/outgoing/a.tif)
 same => n,Set(SIP_CODEC=alaw)
 same => n,Playback(vm-dialout)
 same => n,Set(CALLERID(all)="Fax Esprimo" <1094>)
 same => n,Dial(IAX2/outgoing-raspi111/${EXTEN:8},,M(faxversand))
 same => n,Noop(Faxversand beendet)
 same => n,Hangup()

 ; PDF als Fax versenden
[macro-faxversand] ; Faxversand
; das zu versendende Fax muss im Ordner
; /var/spool/asterisk/fax/outgoing
; entweder al a.tif oder a.pdf vorliegen
exten => s,1,NoOp("Versenden eines Faxes")
same => n,Answer()
same => n,Set(FAXOPT(ecm)=yes)
same => n,Set(FAXOPT(maxrate)=9600)
same => n,Set(FAXOPT(minrate)=2400)
same => n,Set(faxlocation=/var/spool/asterisk/fax/outgoing) 
same => n,Set(faxfile=a.tif) 
same => n,Set(FAXOPT(headerinfo)=Volker Lange-Janson SM5ZBS)
same => n,Set(FAXOPT(localstationid)=1094)
; same => n,System(convert -density 204x196 -depth 2 -monochrome -resize 1728x -units PixelsPerInch /var/spool/asterisk/fax/outgoing/a.pdf -compress Fax /var/spool/asterisk/fax/outgoing/a.tif)
same => n,Set(CHANNEL(hangup_handler_push)=faxergebnis,s,1)
same => n,Wait(2)
same => n,SendFax(${faxlocation}/${faxfile})

; https://docs.asterisk.org/Asterisk_16_Documentation/API_Documentation/Dialplan_Functions/FAXOPT/
same => n,NoOp(STATUS: ${FAXOPT(status)})                   ; Info, ob erfogreich oder gescheiterer Faxversand
same => n,NoOp(RESOLUTION: ${FAXOPT(resolution)})           ; Auflösung des Fax
same => n,NoOp(RATE: ${FAXOPT(rate)})                       ; Geschwindigkeit
same => n,NoOp(PAGES: ${FAXOPT(pages)})                     ; Anzahl übertragener Seiten
same => n,NoOp(REMOTESTATIONID: ${FAXOPT(remotestationid)}) ; 
same => n,NoOp(SESSIONID: ${FAXOPT(sessionid)})             ; 
same => n,NoOp(ERROR: ${FAXOPT(error)})                     ; Fehlermeldung
same => n,HangUp()

[faxergebnis]
exten => s,1,NoOp(STATUS: ${FAXSTATUS})
 same => n,NoOp(RATE: ${FAXBITRATE})
 same => n,NoOp(PAGES: ${FAXPAGES})
 same => n,NoOp(ERROR: ${FAXERROR})
 same => n,Return()
 

The process at a glance: A small Python program with Tkinter copies the selected PDF file as a.pdf into an outgoing folder and starts a call through the Asterisk console. In the dialplan, this call runs exactly as if I had dialed the number on a telephone. The dialplan converts the PDF into a fax TIFF with ImageMagick and sends it with SendFAX. Meanwhile, the program reads the console output and shows in a status window how far along the fax is and whether it arrived. That sounds simple. The devil is in the permissions.

Step 1, install the packages: ImageMagick converts PDF to TIFF, and for that it needs Ghostscript. The interface needs Tkinter. A running Asterisk with the fax module res_fax_spandsp is required. The first command shows whether it is loaded.

sudo asterisk -rx "module show like fax"

sudo apt install imagemagick ghostscript python3-tk

Step 2, adjust ImageMagick: The dialplan calls the convert command through System(). For security reasons, ImageMagick on Ubuntu forbids reading PDF files in its default configuration. You can check whether this is the case on your installation in the file policy.xml. For ImageMagick 6, it is located in /etc/ImageMagick-6/, and for version 7 in /etc/ImageMagick-7/.

grep -n PDF /etc/ImageMagick-6/policy.xml

If there is a line with rights=“none“ and pattern=“PDF“, I change rights=“none“ to rights=“read|write“. This can be done with an editor.

sudo nano /etc/ImageMagick-6/policy.xml

To test it, I put any PDF file into /tmp as test.pdf and convert it as the user that Asterisk runs as. That way I can also see right away whether Asterisk has the necessary permissions. If the file test.tif is created, this part is fine. The parameters are exactly the ones that are also in the dialplan: 204×196 dots per inch, black and white, and a width of 1728 pixels, as fax machines expect.

sudo -u asterisk convert -density 204x196 -depth 2 -monochrome -resize 1728x -units PixelsPerInch /tmp/test.pdf -compress Fax /tmp/test.tif

Step 3, create the outgoing folder: This folder does not exist after the installation, so it has to be created by hand. The program puts the file a.pdf here, and Asterisk creates a.tif from it. Both of us, my user and Asterisk, must be allowed to write here. That is why the folder belongs to the user asterisk and the group asterisk and is writable for the group. The 2 at the beginning of the permissions (setgid) makes sure that new files in this folder automatically get the group asterisk.

sudo mkdir -p /var/spool/asterisk/fax/outgoing

sudo chown asterisk:asterisk /var/spool/asterisk/fax/outgoing

sudo chmod 2775 /var/spool/asterisk/fax/outgoing

Step 4, add your user to the group: My regular user must be a member of the group asterisk so that it can write to the folder and, later, talk to the Asterisk console. Replace BENUTZERNAME (German for „username“) with your own login name.

sudo usermod -aG asterisk BENUTZERNAME

Now comes a trap that is easy to fall into: The new group only takes effect after you completely log out of the desktop and log back in, or after a restart. Opening a new terminal window is not enough. The command id shows whether it worked. The group asterisk must appear in the list of groups in the output.

id

For a quick test without logging in again, the following command opens a shell that already knows the group. This only applies to that one shell, and you then start the program from it.

newgrp asterisk

Step 5, release the Asterisk console: This was the biggest hurdle. Without this step, the call to asterisk -rx as a normal user reports the error messages “Unable to open specified master config file” and “Unable to connect to remote asterisk”. Asterisk is running, but only the user asterisk and root are allowed to talk to it. The program therefore gets no response and cannot start the fax call. The solution has two parts. First, I open the file asterisk.conf.

sudo nano /etc/asterisk/asterisk.conf

In the [files] section, these three lines must be present, each without a semicolon at the beginning of the line. Watch out for typos! In my case, the user name initially read “astersik” instead of “asterisk”, and it took me quite a while to spot the swapped letters.

astctlpermissions = 0660

astctlowner = asterisk

astctlgroup = asterisk

The second part is the permissions on the configuration files. The group asterisk must be allowed to read the directory so that asterisk -rx can open the configuration at all. The directory gets permissions 750 and the files 640. The asterisk wildcard, which stands for all configuration files, must be expanded by root. After chmod 750, my normal user can no longer list the directory, and a simple sudo chmod 640 /etc/asterisk/*.conf reports “No such file or directory”. That is why the detour through bash -c is needed.

sudo chgrp -R asterisk /etc/asterisk

sudo chmod 750 /etc/asterisk

sudo bash -c 'chmod 640 /etc/asterisk/*.conf'

sudo systemctl restart asterisk

The configuration files contain passwords. Anyone who is a member of the group asterisk can now read them. Therefore, only trusted users should be in this group. To check, the socket should now have the permissions srw-rw—-, and the version query must work without sudo.

ls -l /var/run/asterisk/asterisk.ctl

asterisk -rx "core show version"

If the line with the Asterisk version appears, the hardest part is done. If not, the order usually helps: first the configuration, then restart the service, then log out and back in, and only then test.

Step 6, extend the dialplan: This is where the stumbling blocks are that you will hardly find without help. All changes go into the file extensions.conf.

sudo nano /etc/asterisk/extensions.conf

In the macro faxversand, two lines go directly before the line with SendFAX. The first is a hangup handler. It is also executed when the other side hangs up right after the fax and the dialplan would otherwise abort before the result is output. In that case, the fax arrives, but the program never learns about it and reports an abort. The second line is a short pause. It saved the fax to a FritzBox in Germany for me: That FritzBox picks up immediately and sends its fax signals before my Asterisk is ready to send. Without the pause, the fax fails with the message “Timed out waiting for initial communication”.

same => n,Set(CHANNEL(hangup_handler_push)=faxergebnis,s,1)

same => n,Wait(2)

Then the existing line with SendFAX follows directly. The hangup handler needs its own context, which goes at the end of extensions.conf. It outputs the result as NoOp lines, which the program reads.

[faxergebnis]

exten => s,1,NoOp(STATUS: ${FAXSTATUS})

same => n,NoOp(RATE: ${FAXBITRATE})

same => n,NoOp(PAGES: ${FAXPAGES})

same => n,NoOp(ERROR: ${FAXERROR})

same => n,Return()

I also set a caller ID in the dial rule before the Dial. Some remote devices reject calls without a caller number. In my case, the Raspberry Pi initially reported “busy” for the FritzBox in the house as long as my fax arrived without a sender. I did not prove down to the last detail that the missing caller number was the cause. With a number set, it worked anyway. The number and the name can be chosen freely.

same => n,Set(CALLERID(all)="Fax Esprimo" <1094>)

If you still have an old line Set(SIP_CODEC=g722) in your dialplan, change it to alaw or ulaw. Fax needs the G.711 codec, and G.722 distorts the fax signals. In my setup over IAX2, the line has no effect anyway, because alaw is negotiated there. It is just a leftover. Two more notes: Asterisk 20 no longer has chan_sip. A Dial to SIP/… no longer works, so you need PJSIP/… or IAX2/…. And the message “Macro() is deprecated” only appears on the first call after each start and is harmless. After that, reload the dialplan.

sudo asterisk -rx "dialplan reload"

Step 7, start the program: The Python program fax_gui.py can go in any folder. In the interface, you enter the recipient number, select the PDF file, and can adjust the prefix and context. One click on the big button sends the fax. Internally, it starts a call through the Asterisk console, which runs in the dialplan like a call from a telephone. Start it from a session that already has the group asterisk, so after logging in again or from a shell opened with newgrp.

python3 fax_gui.py

The interface also works without drag and drop. If you want to drag the PDF in with the mouse, additionally install the module tkinterdnd2, preferably in a virtual environment, because Ubuntu 24.04 locks pip at the system level. Send the first test fax to a device on your own network. In the status window, the messages appear one after another: “Empfänger wird angerufen” (calling the recipient), “Fax wird übertragen” (transmitting the fax), and finally “Fax erfolgreich gesendet” (fax sent successfully) with the page count and the transmission rate. If there is an error, the status window shows the message from Asterisk, for example “Timed out waiting for initial communication”.

The difficulties at a glance: Almost none of it was a bug in the program. First, the connection to the console failed because of the permissions and the swapped letters in the configuration. Then the new group was not active because I had not logged in again. At first, the program queried the status from Asterisk every one and a half seconds, and I suspected that this was disturbing the fax transmission. That suspicion was not confirmed. I replaced the polling with a one-time reading of the console anyway, and it now runs cleanly. This also revealed a peculiarity: When the Asterisk console writes into a pipe, it buffers the output, and you see nothing for minutes. The program therefore works with a pseudo-terminal. If you want to write the output to a file yourself, use the program script instead of tee. By the way, the log file /var/log/asterisk/full only exists on Ubuntu if you enable it in the file logger.conf. The program no longer needs it. Then there were the faxes that arrived but were reported as “aborted”. The hangup handler helped there. And finally, the fax to the FritzBox in Germany, which only worked with the pause.

The help of the AI Claude: I would not have managed this as quickly on my own. Claude helped me with every one of these points, from reading the error messages and the Asterisk logs, through the permissions, to the Python program and the dialplan lines. To be completely honest: Not every guess was right. A few times the explanation was off, and only the next log showed what was really going on. That is exactly why it is worth doing the following when you run into trouble: copy the error message, the output of the Asterisk console, or a screenshot of the interface into the chat, and narrow things down together step by step. You need patience and have to try out the suggestions. But it saves many hours.

Conclusion: Let’s be honest: Nobody needs to send a fax through a Raspberry Pi, IAX2, SIP, and a self-written Python program anymore. An email would be faster. But as a lesson in Linux permissions, Asterisk, and dealing with error messages, it was priceless, and now it works: select the PDF, type the number, click, and after a minute the status window says “Fax erfolgreich gesendet” (fax sent successfully). The knowledge about permissions, groups, and the dialplan is also very useful for other projects with Asterisk.

Addendum – Improved version with drag & drop: Just drag the PDF into the window, enter the destination number, send, done.

Bildschirmfoto zu 2026 11 30 15 12
Improved version with easier operation.

Video above: On the left, the GUI as a Python script for sending faxes. On the lower right, you can see the Asterisk console on the Ubuntu desktop computer on which the GUI runs. On the upper right is the Asterisk console on the Raspberry Pi, which is connected via IAX2 to the Asterisk on the Ubuntu computer and enables the phone connections over the internet to various providers (e.g., Sipgate).

The Python script for the GUI (graphical user interface): On my computer, the script is located on the desktop.

#!/usr/bin/env python3
"""Fax-GUI für Asterisk (Tkinter) – schlanke Oberfläche in Graublau

Bedienung:
  1. PDF in die große Fläche ziehen (oder auf die Fläche klicken)
  2. Empfängernummer eintragen
  3. "Fax senden"
  Im Ereignisfenster sieht man den Ablauf.

Technik (unverändert zur bisherigen Version):
  - PDF wird als a.pdf in den Ausgangsordner kopiert (Dialplan aus dem Blogartikel)
  - Anruf per Asterisk-Konsole: channel originate Local/<Vorwahl><Nummer>@<Kontext>
  - Fortschritt über eine einzige dauerhafte Konsolenverbindung (asterisk -rnvvv)

Drag & Drop:  pip install tkinterdnd2
(ohne das Paket funktioniert ein Klick auf die Fläche zum Auswählen)
"""
import json
import os
import pty
import re
import shutil
import subprocess
import threading
import time
import tkinter as tk
from datetime import datetime
from pathlib import Path
from tkinter import filedialog, messagebox, ttk

try:
    from tkinterdnd2 import DND_FILES, TkinterDnD
    BaseTk = TkinterDnD.Tk
    HAS_DND = True
except Exception:
    BaseTk = tk.Tk
    HAS_DND = False

# ----------------------------------------------------------- feste Einstellungen
ASTERISK_CMD = "asterisk"
OUTGOING_DIR = Path("/var/spool/asterisk/fax/outgoing")
CONTEXT = "telefone"
PREFIX = "1094"

CONFIG_FILE = Path.home() / ".config" / "fax-gui.json"
DEFAULTS = {"pdf_dir": str(Path.home()), "history": []}

# ------------------------------------------------------------------- Farben
C_BG = "#dde3ea"        # Fensterhintergrund (helles Graublau)
C_HEAD = "#44596f"      # Kopfzeile, dunkles Graublau
C_ACCENT = "#5b7d9f"    # Button / Akzent
C_ACCENT_DK = "#46657f"  # Button gedrückt
C_DROP = "#eef2f6"      # Dropfläche
C_DROP_HI = "#cfdbe8"   # Dropfläche beim Darüberziehen
C_BORDER = "#7f97ae"
C_TEXT = "#26333f"
C_MUTED = "#6a7b8c"
C_OK = "#2e7d4f"
C_ERR = "#b03a3a"
C_LOG_BG = "#f6f8fa"

NOOP_RE = re.compile(r'NoOp\("[^"]*", "(STATUS|PAGES|RATE|ERROR): ?([^"]*)"')
ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")


def read_lines(fd):
    """Liefert Zeilen aus einem Pseudo-Terminal."""
    buf = b""
    while True:
        try:
            chunk = os.read(fd, 4096)
        except OSError:
            return
        if not chunk:
            return
        buf += chunk
        while b"\n" in buf:
            line, buf = buf.split(b"\n", 1)
            yield ANSI_RE.sub("", line.decode("utf-8", "replace")).strip()


def load_cfg():
    cfg = dict(DEFAULTS)
    try:
        cfg.update(json.loads(CONFIG_FILE.read_text()))
    except (OSError, ValueError):
        pass
    return cfg


def save_cfg(cfg):
    try:
        CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
        CONFIG_FILE.write_text(json.dumps(cfg, indent=2))
    except OSError:
        pass


class FaxApp(BaseTk):
    def __init__(self):
        super().__init__()
        self.title("Fax senden")
        self.configure(bg=C_BG)
        self.minsize(540, 640)
        self.geometry("580x700")
        self.cfg = load_cfg()
        self.pdf = None          # gewählte PDF (Path)
        self.busy = False
        self.build()

    # ---------------------------------------------------------------- GUI
    def build(self):
        style = ttk.Style(self)
        try:
            style.theme_use("clam")
        except tk.TclError:
            pass
        style.configure("TFrame", background=C_BG)
        style.configure("TLabel", background=C_BG, foreground=C_TEXT,
                        font=("Sans", 11))
        style.configure("Small.TLabel", foreground=C_MUTED, font=("Sans", 10))
        style.configure("TCombobox", fieldbackground="white", padding=6)
        style.configure("Send.TButton", font=("Sans", 15, "bold"), padding=12,
                        background=C_ACCENT, foreground="white",
                        bordercolor=C_ACCENT_DK, focuscolor=C_ACCENT)
        style.map("Send.TButton",
                  background=[("disabled", "#a9b8c7"), ("pressed", C_ACCENT_DK),
                              ("active", "#6a8cae")],
                  foreground=[("disabled", "#e8edf2")])
        style.configure("Horizontal.TProgressbar", troughcolor="#c3cdd8",
                        background=C_ACCENT, bordercolor=C_BG,
                        lightcolor=C_ACCENT, darkcolor=C_ACCENT)

        # Kopfzeile
        head = tk.Frame(self, bg=C_HEAD)
        head.pack(fill="x")
        tk.Label(head, text="Fax senden", bg=C_HEAD, fg="white",
                 font=("Sans", 18, "bold")).pack(side="left", padx=20, pady=14)

        body = ttk.Frame(self, padding=(20, 16, 20, 16))
        body.pack(fill="both", expand=True)
        body.columnconfigure(0, weight=1)
        body.rowconfigure(5, weight=1)

        # 1) Dropfläche
        ttk.Label(body, text="1.  PDF-Datei").grid(row=0, column=0, sticky="w")
        self.drop = tk.Canvas(body, height=140, bg=C_DROP, highlightthickness=0,
                              cursor="hand2")
        self.drop.grid(row=1, column=0, sticky="ew", pady=(4, 14))
        self.drop.bind("<Configure>", lambda e: self.draw_drop())
        self.drop.bind("<Button-1>", lambda e: self.browse())

        # 2) Nummer
        ttk.Label(body, text="2.  Empfängernummer").grid(row=2, column=0, sticky="w")
        self.num = ttk.Combobox(body, font=("Sans", 16),
                                values=self.cfg["history"])
        self.num.grid(row=3, column=0, sticky="ew", pady=(4, 14))
        self.num.focus_set()

        # 3) Senden
        self.send_btn = ttk.Button(body, text="Fax senden", style="Send.TButton",
                                   command=self.send)
        self.send_btn.grid(row=4, column=0, sticky="ew", pady=(0, 6))
        self.bar = ttk.Progressbar(body, mode="indeterminate", length=100)
        self.bar.grid(row=4, column=0, sticky="sew")
        self.bar.grid_remove()

        # Ereignisfenster
        logf = ttk.Frame(body)
        logf.grid(row=5, column=0, sticky="nsew", pady=(14, 0))
        logf.columnconfigure(0, weight=1)
        logf.rowconfigure(1, weight=1)
        ttk.Label(logf, text="Ereignisse", style="Small.TLabel").grid(
            row=0, column=0, sticky="w")
        self.log_box = tk.Text(logf, height=9, state="disabled", wrap="word",
                               font=("Monospace", 10), bg=C_LOG_BG, fg=C_TEXT,
                               relief="flat", highlightthickness=1,
                               highlightbackground=C_BORDER, padx=8, pady=6)
        self.log_box.grid(row=1, column=0, sticky="nsew")
        sb = ttk.Scrollbar(logf, command=self.log_box.yview)
        sb.grid(row=1, column=1, sticky="ns")
        self.log_box.configure(yscrollcommand=sb.set)
        self.log_box.tag_configure("ok", foreground=C_OK,
                                   font=("Monospace", 10, "bold"))
        self.log_box.tag_configure("err", foreground=C_ERR,
                                   font=("Monospace", 10, "bold"))
        self.log_box.tag_configure("time", foreground=C_MUTED)

        if HAS_DND:
            for w in (self, self.drop):
                w.drop_target_register(DND_FILES)
                w.dnd_bind("<<Drop>>", self.on_drop)
            self.drop.dnd_bind("<<DropEnter>>", lambda e: self.hilight(True))
            self.drop.dnd_bind("<<DropLeave>>", lambda e: self.hilight(False))
        else:
            self.log("Hinweis: Für Drag & Drop 'pip install tkinterdnd2' "
                     "ausführen. Klick auf die Fläche öffnet die Dateiauswahl.")
        self.bind("<Return>", lambda e: self.send())

    def draw_drop(self, hi=False):
        c = self.drop
        c.delete("all")
        c.configure(bg=C_DROP_HI if hi else C_DROP)
        w, h = c.winfo_width(), c.winfo_height()
        c.create_rectangle(6, 6, w - 6, h - 6, outline=C_BORDER, width=2,
                           dash=(8, 5))
        if self.pdf:
            c.create_text(w / 2, h / 2 - 14, text=self.pdf.name, fill=C_TEXT,
                          font=("Sans", 14, "bold"), width=w - 40)
            c.create_text(w / 2, h / 2 + 26,
                          text="Andere PDF hineinziehen oder klicken zum Ändern",
                          fill=C_MUTED, font=("Sans", 10))
        else:
            main = "PDF hier hineinziehen" if HAS_DND else "Hier klicken"
            c.create_text(w / 2, h / 2 - 12, text=main, fill=C_TEXT,
                          font=("Sans", 15, "bold"))
            c.create_text(w / 2, h / 2 + 18, text="oder klicken, um eine Datei "
                          "auszuwählen", fill=C_MUTED, font=("Sans", 10))

    def hilight(self, on):
        self.draw_drop(hi=on)

    def log(self, msg, tag=None):
        def _do():
            self.log_box.configure(state="normal")
            self.log_box.insert("end", f"{datetime.now():%H:%M:%S}  ", "time")
            self.log_box.insert("end", msg + "\n", tag or ())
            self.log_box.see("end")
            self.log_box.configure(state="disabled")
        self.after(0, _do)

    # --------------------------------------------------------------- Datei
    def browse(self):
        if self.busy:
            return
        name = filedialog.askopenfilename(
            title="PDF auswählen", initialdir=self.cfg["pdf_dir"],
            filetypes=[("PDF-Dateien", "*.pdf"), ("Alle Dateien", "*.*")])
        if name:
            self.set_pdf(Path(name))

    def set_pdf(self, path):
        if path.suffix.lower() != ".pdf":
            messagebox.showwarning("Fax", "Bitte eine PDF-Datei wählen.")
            return
        self.pdf = path
        self.cfg["pdf_dir"] = str(path.parent)
        self.draw_drop()
        self.log(f"PDF gewählt: {path.name}")
        self.num.focus_set()

    def on_drop(self, event):
        self.hilight(False)
        if self.busy:
            return
        for name in self.tk.splitlist(event.data):
            self.set_pdf(Path(name))
            break

    # -------------------------------------------------------------- Senden
    def send(self):
        if self.busy:
            return
        number = re.sub(r"[\s\-/()]", "", self.num.get())
        if not re.fullmatch(r"\+?\d+", number):
            messagebox.showwarning("Fax", "Bitte eine gültige Empfängernummer eingeben.")
            return
        number = number.lstrip("+")
        if not self.pdf or not self.pdf.exists():
            messagebox.showwarning("Fax", "Bitte zuerst eine PDF-Datei auswählen.")
            return
        if not messagebox.askyesno("Fax senden",
                                   f"„{self.pdf.name}“ an {number} faxen?"):
            return
        hist = [number] + [h for h in self.cfg["history"] if h != number]
        self.cfg["history"] = hist[:15]
        save_cfg(self.cfg)
        self.num["values"] = self.cfg["history"]
        self.set_busy(True)
        threading.Thread(target=self.worker, args=(self.pdf, number),
                         daemon=True).start()

    def set_busy(self, busy):
        def _do():
            self.busy = busy
            if busy:
                self.send_btn.configure(state="disabled")
                self.bar.grid()
                self.bar.start(12)
            else:
                self.bar.stop()
                self.bar.grid_remove()
                self.send_btn.configure(state="normal")
        self.busy = busy
        self.after(0, _do)

    def ast(self, command):
        r = subprocess.run([ASTERISK_CMD, "-rx", command],
                           capture_output=True, text=True, timeout=20)
        return (r.stdout + r.stderr).strip()

    def worker(self, pdf, number):
        con = timer = master = None
        try:
            self.log(f"Kopiere {pdf.name} nach {OUTGOING_DIR}/a.pdf …")
            shutil.copyfile(pdf, OUTGOING_DIR / "a.pdf")
            try:
                (OUTGOING_DIR / "a.tif").unlink()
            except OSError:
                pass

            # Eine dauerhafte Konsolenverbindung zum Mitlesen; Pseudo-Terminal,
            # sonst puffert asterisk die Ausgabe bei einer Pipe
            master, slave = pty.openpty()
            con = subprocess.Popen([ASTERISK_CMD, "-rnvvv"],
                                   stdin=slave, stdout=slave, stderr=slave,
                                   close_fds=True)
            os.close(slave)
            timer = threading.Timer(900, con.terminate)
            timer.start()
            time.sleep(1.5)

            target = f"Local/{PREFIX}{number}@{CONTEXT}"
            self.log(f"Starte Anruf {target} …")
            res = self.ast(f"channel originate {target} application Wait 900")
            if "rror" in res or "nable" in res or "No such" in res:
                self.log("Asterisk meldet: " + res, "err")
                return
            self.log("PDF wird in TIFF umgewandelt, Verbindung wird aufgebaut …")
            self.follow(master, PREFIX + number)
        except subprocess.TimeoutExpired:
            self.log("Fehler: Asterisk-Konsole antwortet nicht.", "err")
        except (OSError, subprocess.SubprocessError) as exc:
            self.log(f"Fehler: {exc}", "err")
        finally:
            if timer:
                timer.cancel()
            if con:
                con.terminate()
            if master is not None:
                try:
                    os.close(master)
                except OSError:
                    pass
            self.set_busy(False)

    def follow(self, fd, key):
        """Liest die Konsolenausgabe mit und meldet den Fortschritt."""
        found, called, sending = {}, False, False
        for line in read_lines(fd):
            if not line:
                continue
            if "WARNING[" in line or "ERROR[" in line:
                self.log("Asterisk: " + line[:200], "err")
            if not called and "Called " in line and "Local/" not in line:
                called = True
                self.log("Empfänger wird angerufen …")
            if not sending and "Executing" in line and "SendFAX" in line:
                sending = True
                self.log("Fax wird übertragen …")
            m = NOOP_RE.search(line)
            if m:
                found[m.group(1)] = m.group(2).strip()
            if f"Spawn extension ({CONTEXT}, {key}" in line and "exited" in line:
                break
        else:
            self.log("Zeitüberschreitung oder Verbindung zur Konsole verloren – "
                     "bitte in der Asterisk-Konsole nachsehen.", "err")
            return
        status = found.get("STATUS")
        if status == "SUCCESS":
            self.log(f"✔ Fax erfolgreich gesendet – {found.get('PAGES', '?')} "
                     f"Seite(n), {found.get('RATE', '?')} bit/s", "ok")
        elif status:
            self.log(f"✘ Fax fehlgeschlagen: {status} {found.get('ERROR', '')}", "err")
        elif sending:
            self.log("✘ Übertragung abgebrochen (kein Faxergebnis).", "err")
        else:
            self.log("✘ Empfänger nicht erreicht (besetzt, nicht erreichbar oder "
                     "Kanaltyp fehlt) – siehe Asterisk-Meldung oben.", "err")


if __name__ == "__main__":
    FaxApp().mainloop()

For the script to run, tkinterdnd2 must be installed:

pip install --user --break-system-packages tkinterdnd2

There are several ways to do this. This one worked for me. The package ends up in ~/.local/lib/python3.12/site-packages. System packages are not modified. The “risk” in the warning message mainly concerns overwriting system packages, and that does not happen with --user. After that, you start the GUI as usual with python3 fax_gui.py.

Sending faxes via Sipgate: If sending faxes via Sipgate fails, change [macro-faxversand]. Tested with a fax to a FritzBox via Sipgate.

 ; PDF als Fax versenden
[macro-faxversand] ; Faxversand
; das zu versendende Fax muss im Ordner
; /var/spool/asterisk/fax/outgoing
; entweder al a.tif oder a.pdf vorliegen
exten => s,1,NoOp("Versenden eines Faxes")
same => n,Answer()
same => n,Set(FAXOPT(ecm)=no)
same => n,Set(FAXOPT(modem)=v27,v29)
same => n,Set(FAXOPT(maxrate)=9600) ; war 9600
same => n,Set(FAXOPT(minrate)=4800) ; war 2400
same => n,Set(faxlocation=/var/spool/asterisk/fax/outgoing) 
same => n,Set(faxfile=a.tif) 
same => n,Set(FAXOPT(headerinfo)=Volker Lange-Janson SM5ZBS)
same => n,Set(FAXOPT(localstationid)=1094)
; same => n,System(convert -density 204x196 -depth 2 -monochrome -resize 1728x -units PixelsPerInch /var/spool/asterisk/fax/outgoing/a.pdf -compress Fax /var/spool/asterisk/fax/outgoing/a.tif)
same => n,Set(CHANNEL(hangup_handler_push)=faxergebnis,s,1)
same => n,Wait(2)
same => n,SendFax(${faxlocation}/${faxfile})

; https://docs.asterisk.org/Asterisk_16_Documentation/API_Documentation/Dialplan_Functions/FAXOPT/
same => n,NoOp(STATUS: ${FAXOPT(status)})                   ; Info, ob erfogreich oder gescheiterer Faxversand
same => n,NoOp(RESOLUTION: ${FAXOPT(resolution)})           ; Auflösung des Fax
same => n,NoOp(RATE: ${FAXOPT(rate)})                       ; Geschwindigkeit
same => n,NoOp(PAGES: ${FAXOPT(pages)})                     ; Anzahl übertragener Seiten
same => n,NoOp(REMOTESTATIONID: ${FAXOPT(remotestationid)}) ; 
same => n,NoOp(SESSIONID: ${FAXOPT(sessionid)})             ; 
same => n,NoOp(ERROR: ${FAXOPT(error)})                     ; Fehlermeldung
same => n,HangUp()

[faxergebnis]
exten => s,1,NoOp(STATUS: ${FAXSTATUS})
 same => n,NoOp(RATE: ${FAXBITRATE})
 same => n,NoOp(PAGES: ${FAXPAGES})
 same => n,NoOp(ERROR: ${FAXERROR})
 same => n,Return()

The fast but problematic V.17 modem was disabled. Only the V.27 and V.29 modems are allowed. This limited the maximum transmission rate to 9600. ECM was switched off. You may turn it back on if faxes with many pages cause problems. A 28-page fax was sent through Sipgate to a FritzBox in a transmission time of 14 minutes.

In addition, in the sip.conf on the Raspberry Pi, I forced the Sipgate peer to use only the audio codec alaw, with disallow=all followed by allow=alaw.

[sipgate]
context=sipgate-in
host=sipgate.de
username=.......e0
secret=...
fromuser=.......e0
fromdomain=sipgate.de
canreinvite=no
qualify=yes
nat=force_rport
registertimeout=600
type=friend
disallow=all
allow=alaw

In the iax.conf, too, I turned off the jitter buffer (jitterbuffer=no) for the connection between the Esprimo and the Raspberry Pi, turned off trunk mode (trunk=no), and allowed only alaw (disallow=all and allow=alaw), so that the fax signal is neither converted nor shifted in time along the way.

It is all not that simple until the analog data transmission of the fax signal works over a third-party SIP connection while an IAX2 link sits in between.