How exactly to attach a file to an email using the API ?
Question asked by Curtis Kropar www.HawaiianHope.org - 6/12/2025 at 1:35 PM
Answered
I got the API to work to send out an email to a list.  Awesome !

Now, How exactly do I attach a file to that email ?  The documentation is not really clear... "attachguid" ?

Anyone have an example ?  I am currently using ASP (vbscript) for testing

www.HawaiianHope.org - Providing technology services to non profit organizations, low income families, homeless shelters, clean and sober houses and prisoner reentry programs. Since 2015, We have refurbished over 11,000 Computers !

bump
www.HawaiianHope.org - Providing technology services to non profit organizations, low income families, homeless shelters, clean and sober houses and prisoner reentry programs. Since 2015, We have refurbished over 11,000 Computers !
Zach Sylvester Replied
Employee Post Marked As Answer
Hi Curtis, 

Here is an example in python on how todo this. 


#!/usr/bin/env python3
"""
SmarterMail API - Send Email with Attachment
=============================================
This script authenticates with SmarterMail, uploads a file attachment,
and sends an email with that attachment via the REST API.

REQUIREMENTS:
    pip install requests

USAGE:
    1. Edit the configuration variables below
    2. Run: python send_with_attachment.py

THIS SCRIPT IS READ-ONLY SAFE: It only sends one email. It does not
modify mailbox settings, delete messages, or alter any server config.
"""

import uuid
import sys
import requests

# ============================================================
#  CONFIGURATION — Edit these values
# ============================================================
SMARTERMAIL_URL = "https://mail.example.com"       # Your SmarterMail server URL
USERNAME        = "user@example.com"               # Full email address
PASSWORD        = "your-password"                  # Account password
FILE_PATH       = r"C:\path\to\document.pdf"       # Full path to the file to attach

RECIPIENT       = "recipient@example.com"          # Who to send to
SUBJECT         = "Test email with attachment"     # Email subject
BODY_HTML       = "<p>Hello, please see the attached file.</p>"  # HTML body
# ============================================================


def authenticate(base_url, username, password):
    """Step 1: Authenticate and get an access token."""
    url = f"{base_url}/api/v1/auth/authenticate-user"
    payload = {
        "username": username,
        "password": password
    }
    resp = requests.post(url, json=payload)
    resp.raise_for_status()
    data = resp.json()

    if not data.get("success"):
        print(f"ERROR: Authentication failed: {data.get('message', 'Unknown error')}")
        sys.exit(1)

    print(f"Authenticated as: {data.get('emailAddress', username)}")
    return data["accessToken"]


def upload_attachment(base_url, token, attach_guid, file_path):
    """Step 2: Upload a file attachment using the generated GUID."""
    url = f"{base_url}/api/v1/mail/attachment/{attach_guid}"
    headers = {
        "Authorization": f"Bearer {token}"
    }

    with open(file_path, "rb") as f:
        # The API expects exactly one file sent as multipart form data
        files = {
            "file": (file_path.split("\\")[-1].split("/")[-1], f, "application/octet-stream")
        }
        resp = requests.post(url, headers=headers, files=files)

    resp.raise_for_status()
    data = resp.json()

    if not data.get("success"):
        print(f"ERROR: Attachment upload failed: {data.get('message', 'Unknown error')}")
        sys.exit(1)

    print(f"Attachment uploaded successfully (GUID: {attach_guid})")


def send_message(base_url, token, attach_guid, from_addr, to_addr, subject, body_html):
    """Step 3: Send the email, referencing the attachment GUID."""
    url = f"{base_url}/api/v1/mail/message-put"
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    payload = {
        "from": from_addr,
        "to": to_addr,
        "subject": subject,
        "messageHTML": body_html,
        "attachmentGuid": attach_guid
    }
    resp = requests.post(url, headers=headers, json=payload)
    resp.raise_for_status()
    data = resp.json()

    if not data.get("success"):
        print(f"ERROR: Send failed: {data.get('message', 'Unknown error')}")
        sys.exit(1)

    print("Email sent successfully!")


def main():
    # Generate a unique GUID to group attachments for this message
    attach_guid = str(uuid.uuid4())

    print(f"Sending email to {RECIPIENT} with attachment: {FILE_PATH}")
    print("-" * 50)

    # Step 1: Authenticate
    token = authenticate(SMARTERMAIL_URL, USERNAME, PASSWORD)

    # Step 2: Upload the attachment
    upload_attachment(SMARTERMAIL_URL, token, attach_guid, FILE_PATH)

    # Step 3: Send the email with the attachment
    send_message(SMARTERMAIL_URL, token, attach_guid, USERNAME, RECIPIENT, SUBJECT, BODY_HTML)

    print("-" * 50)
    print("Done!")


if __name__ == "__main__":
    main()


I hope this helps. 


Kind Regards, 
Zach Sylvester Software Developer SmarterTools Inc. www.smartertools.com

Reply to Thread

Enter the verification text