# Gmail Forward via API — Verified Pattern (2026-05-12)

## When to use
Need to forward emails from the LFCS Gmail inbox (michael.mcloughlin@lfcs.com.au) to admin@lfcs.com.au or another address.

## Verified working code

```python
#!/usr/bin/env python3
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
import urllib.request, json, base64, email

creds = Credentials.from_authorized_user_file('/root/.hermes/google_token.json', [
    'https://www.googleapis.com/auth/gmail.readonly',
    'https://www.googleapis.com/auth/gmail.send'
])
creds.refresh(Request())

msg_ids = ['id1', 'id2', 'id3']

for i, msg_id in enumerate(msg_ids):
    # 1. Get raw message
    url = f'https://gmail.googleapis.com/gmail/v1/users/me/messages/{msg_id}?format=raw'
    req = urllib.request.Request(url, headers={'Authorization': f'Bearer {creds.token}'})
    with urllib.request.urlopen(req) as r:
        data = json.loads(r.read())
        raw_b64 = data['raw']
        # base64url decode
        pad = len(raw_b64) % 4
        if pad: raw_b64 += '=' * (4 - pad)
        msg_bytes = base64.urlsafe_b64decode(raw_b64)

    original = email.message_from_bytes(msg_bytes)
    orig_subject = original.get('Subject', '(no subject)')

    # 2. Build forwarded raw message (message/rfc822 format)
    fwd_raw = (
        f"From: michael.mcloughlin@lfcs.com.au\r\n"
        f"To: admin@lfcs.com.au\r\n"
        f"Subject: Fwd: {orig_subject}\r\n"
        f"Content-Type: message/rfc822; charset=utf-8\r\n\r\n"
    ).encode('utf-8') + msg_bytes

    # 3. base64url encode (no padding)
    b64_fwd = base64.urlsafe_b64encode(fwd_raw).decode('ascii').rstrip('=')

    # 4. Send via Gmail API
    send_url = 'https://gmail.googleapis.com/gmail/v1/users/me/messages/send'
    body = json.dumps({'raw': b64_fwd}).encode('utf-8')
    send_req = urllib.request.Request(send_url, data=body, headers={
        'Authorization': f'Bearer {creds.token}',
        'Content-Type': 'application/json'
    })
    with urllib.request.urlopen(send_req) as r:
        result = json.loads(r.read())
        print(f'Sent: {orig_subject[:60]} -> {result.get("id")}')
```

## Key decisions

- Uses `format=raw` to get the full original MIME message, then wraps it as `message/rfc822` for forwarding
- base64url encoding (RFC 4648) — standard base64 with `+`/`/` replaced and `=` padding stripped
- No SMTP needed — direct Gmail API send, authenticated as michael.mcloughlin@lfcs.com.au
- Works for any number of emails; loop and batch

## Finding emails to forward

```python
# Search
query = urllib.parse.quote('from:decprojects.com.au after:2026/05/11')
url = f'https://gmail.googleapis.com/gmail/v1/users/me/messages?q={query}&maxResults=20'
# Returns list of {id} — pass to forward script
```

## Common sender addresses (LFCS context)
- Robert Logan: `Robert.Logan@decprojects.com.au` — bridge tender correspondence
- Search domain: `decprojects.com.au` (not "tenders.dec")