modSendEmail.bas

' ============================================================
' Copyright (c) 2025-2026 Peter Bryant (Corylus Business Systems)
'                    and  Andrew Richards (The IT Service Ltd)
' Part of VBAuth - https://vbauth.com
' Licensed under the MIT Licence - see LICENCE.txt
' This copyright notice must not be removed or altered.
' ============================================================

' ============================================================
' modSendEmail - VBAuth example: Send email via Microsoft Graph
' ============================================================
' Demonstrates the standard VBAuth call pattern for a POST request:
'   1. Set intAppID to identify the API configuration record
'   2. Call SetEntraAPPIdValues to load credentials and build URL
'   3. Call AcquireBearerToken to obtain or reuse a valid token
'   4. Build the JSON payload for the API call
'   5. POST to the Graph API endpoint
'
' Admin table record required: AppID = 4
'   Verb:        POST
'   URLPart1:    https://graph.microsoft.com/v1.0/me/sendMail
'   ScopeClaims: Mail.Send
'
' Note: sends email as the authenticated user.
' ============================================================

' ------------------------------------------------------------
' DEPENDENCIES - required modules in any target database:
'   modVBAuthGlobalConstants  (globals, SetEntraAPPIdValues,
'                              AcquireBearerToken)
'   JSONConverter              (Tim Hall VBA-JSON parser)
' ------------------------------------------------------------
' CALLING EXAMPLE (no auth code required):
'   Dim strPayload As String
'   Dim strResult  As String
'   strPayload = BuildSendMailPayload(
'       "to@example.com", "", "",
'       "Subject", "Body text", False, True)
'   If SendEmail(strPayload, strResult) Then
'       MsgBox "Sent"
'   End If


Option Compare Database
Option Explicit

Public Function SendEmail(strPayload As String, ByRef strResult As String) As Boolean
Dim http        As Object
Dim strResponse As String
Dim objJson     As Object

    SendEmail = False
    strResult = ""

    On Error GoTo ErrorHandler

    intAppID = 4
    blnResult = SetEntraAPPIdValues(False, False)
    If blnResult = False Then
        'note the called function will feedback the error situation via strMessage
        strResult = strMessage
        Exit Function
    End If

    blnResult = AcquireBearerToken(strClientID, strTenantID, strScopeRequested)
    If blnResult = False Then
        'note the called function will feedback the error situation via strMessage
        Debug.Print "AcquireBearerToken failed: " & strMessage
        strResult = strMessage
        Exit Function
    End If

    ' POST the email payload to the Graph API
    Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
    http.Open strGraphAPI_Verb, strGraphAPI_URL, False
    http.setRequestHeader "Authorization", "Bearer " & strBearerToken
    http.setRequestHeader "Content-Type", "application/json"
    http.setRequestHeader "Accept", "application/json"
    http.setTimeouts lngHTTPTimeout, lngHTTPTimeout, lngHTTPTimeout, lngHTTPTimeout
    http.Send strPayload
    Debug.Print "HTTP Status: " & http.status
    Debug.Print "Response: " & http.ResponseText

    ' Graph returns 202 Accepted for a successful send - no response body
    If http.status = 202 Then
        SendEmail = True
    Else
        strResult = "HTTP " & http.status & ": " & http.ResponseText
    End If
    Exit Function

ErrorHandler:
    If Err.Number = -2147012894 Then
        strResult = "The request to Microsoft Graph timed out after " & _
                    lngHTTPTimeout / 1000 & " seconds. " & _
                    "Please check your network connection and try again."
    Else
        strResult = "Request failed: " & Err.Number & " - " & Err.Description
    End If
    MsgBox strResult, vbCritical, "Send Email"
End Function

' ============================================================
' BuildSendMailPayload
' Constructs the JSON request body for the Graph sendMail
' endpoint from the supplied field values.
' strTo, strCC, strBCC are comma-separated address lists.
' blnBodyHTML controls whether body ContentType is HTML or Text.
' blnSaveToSentItems controls the saveToSentItems flag.
' Returns the complete JSON string ready to POST.
' ============================================================
Public Function BuildSendMailPayload( _
        strTo As String, _
        strCC As String, _
        strBCC As String, _
        strSubject As String, _
        strBody As String, _
        blnBodyHTML As Boolean, _
        blnSaveToSentItems As Boolean) As String

Dim strBodyType     As String
Dim strToJSON       As String
Dim strCCJSON       As String
Dim strBCCJSON      As String

    strBodyType = IIf(blnBodyHTML, "HTML", "Text")

    strToJSON = BuildRecipientArray(strTo)
    strCCJSON = BuildRecipientArray(strCC)
    strBCCJSON = BuildRecipientArray(strBCC)

    BuildSendMailPayload = "{" & _
        """message"":{" & _
            """subject"":""" & JsonEscape(strSubject) & """," & _
            """body"":{" & _
                """contentType"":""" & strBodyType & """," & _
                """content"":""" & JsonEscape(strBody) & """" & _
            "}," & _
            """toRecipients"":" & strToJSON & "," & _
            IIf(strCC <> "", """ccRecipients"":" & strCCJSON & ",", "") & _
            IIf(strBCC <> "", """bccRecipients"":" & strBCCJSON & ",", "") & _
        "}," & _
        """saveToSentItems"":""" & LCase(CStr(blnSaveToSentItems)) & """" & _
    "}"

End Function

' ============================================================
' BuildRecipientArray
' Converts a comma-separated list of email addresses into the
' Graph API recipient array format:
'   [{"emailAddress":{"address":"a@b.com"}}, ...]
' Returns "[]" for an empty input string.
' ============================================================
Private Function BuildRecipientArray(strAddresses As String) As String
' Converts a semicolon or comma -separated list of email addresses into a
' Graph API recipient array: [{"emailAddress":{"address":"a@b.com"}},...]
Dim arrAddresses()  As String
Dim strAddress      As String
Dim strArray        As String
Dim i               As Integer

    If Trim(strAddresses) = "" Then
        BuildRecipientArray = "[]"
        Exit Function
    End If

    arrAddresses = Split(Replace(strAddresses, ";", ","), ",")
    strArray = "["
    For i = 0 To UBound(arrAddresses)
        strAddress = Trim(arrAddresses(i))
        If strAddress <> "" Then
            If strArray <> "[" Then strArray = strArray & ","
            strArray = strArray & _
                "{""emailAddress"":{""address"":""" & JsonEscape(strAddress) & """}}"
        End If
    Next i
    strArray = strArray & "]"
    BuildRecipientArray = strArray

End Function

' ============================================================
' JsonEscape
' Escapes special characters in a string for safe embedding
' as a JSON string value. Handles backslash, double-quote,
' CR/LF and tab characters.
' ============================================================
Private Function JsonEscape(strValue As String) As String
' Escapes special characters for embedding in a JSON string value
    strValue = Replace(strValue, "\", "\\")
    strValue = Replace(strValue, """", "\""")
    strValue = Replace(strValue, vbCrLf, "\n")
    strValue = Replace(strValue, vbCr, "\n")
    strValue = Replace(strValue, vbLf, "\n")
    strValue = Replace(strValue, vbTab, "\t")
    JsonEscape = strValue
End FunctionCode language: PHP (php)
Updated on April 4, 2026