Bahar_Engineer
Bahar_Engineer

Reputation: 29

golang sending email with azure communication service

I have an azure communication service template for sending email. Our project is in golang and i need to implement a method to send email based on azure communication service. I found karim-w library but not worked for me and it's complicated.

I implemented this code in python and it's working correctly. I wanna implement this in golang too.

Any idea or suggestion?

from azure.communication.email import EmailClient
def main():
    try:
        connection_string = "endpoint=https://announcement.unitedstates.communication.azure.com/;accesskey=***********"
        client = EmailClient.from_connection_string(connection_string)
        message = {
            "senderAddress": "[email protected]",
            "recipients":  {
                "to": [{"address": "[email protected]" }],
            },
            "content": {
                "subject": "Test Email",
                "plainText": "Hello world via email.",
            }
        }
        poller = client.begin_send(message)
        result = poller.result()
    except Exception as ex:
        print(ex)
main()

Thanks in advance

Upvotes: 1

Views: 474

Answers (2)

Garima Bathla
Garima Bathla

Reputation: 41

I can't comment on the above-accepted answer; hence, I am providing another answer.

Please note a few changes for the sample code to work in 2024.

  1. connection string:
    • remove https:// as it is appended by the library.
    • remove the leading / at the end of the communication-server. It leads to the wrong auth header and results in 401.

example:

  • connectionString := "endpoint=demo-communication-server.unitedstates.communication.azure.com;accesskey=your-access-key"
  1. The Azure rest API requires attachments to be passed in even though you have no attachments. here is the updated payload that works.
payload: = emails.Payload {
  Headers: emails.Headers {
    ClientCorrelationID: "some-correlation-id",
    ClientCustomHeaderName: "some-custom-header",
  },
  SenderAddress: "<[email protected]>",
  Content: emails.Content {
    Subject: "Fabric tenant abcde wants to upgrade to paid offer",
    PlainText: "This is being generated from dev-server.",
    HTML: "<p>This is a <strong>test</strong> email.</p>",
  },
  Recipients: emails.Recipients {
    To: [] emails.ReplyTo {
      {
        Address: "[email protected]",
        DisplayName: "Garima Bathla",
      },
    },
  },
  Attachments: [] emails.Attachment {},
  UserEngagementTrackingDisabled: false,
}
  1. The sender's email address needs to be in this format:
SenderAddress: "<[email protected]>",

Upvotes: 0

Architect Jamie
Architect Jamie

Reputation: 2569

There's email functionality in an unofficial SDK. Credit to Karim. You can try something like this:

package main

import (
    "context"
    "fmt"
    "strings"

    "github.com/Karim-W/go-azure-communication-services/emails"
)

func main() {
    connectionString := "endpoint=https://announcement.unitedstates.communication.azure.com/;accesskey=***********"

    // Parse connection string
    endpoint, accessKey := parseConnectionString(connectionString)

    // Create new client
    client := emails.NewClient(
        endpoint,
        accessKey,
        nil, // version (uses defaultAPIVersion)
    )

    // Prepare payload
    payload := emails.Payload{
        Headers: emails.Headers{
            ClientCorrelationID:    "some-correlation-id",
            ClientCustomHeaderName: "some-custom-header",
        },
        SenderAddress: "[email protected]",
        Content: emails.Content{
            Subject:   "Test Email",
            PlainText: "This is a test email.",
            HTML:      "<p>This is a <strong>test</strong> email.</p>",
        },
        Recipients: emails.Recipients{
            To: []emails.ReplyTo{
                {
                    Address:     "[email protected]",
                    DisplayName: "Recipient Name",
                },
            },
        },
        UserEngagementTrackingDisabled: false,
    }

    // Send email
    ctx := context.Background()
    result, err := client.SendEmail(ctx, payload)
    if err != nil {
        fmt.Println("Error sending email:", err)
        return
    }

    fmt.Println("Email sent successfully:", result)
}

// parseConnectionString parses the connection string to extract endpoint and access key
func parseConnectionString(connStr string) (string, string) {
    parts := strings.Split(connStr, ";")
    var endpoint, accessKey string
    for _, part := range parts {
        if strings.HasPrefix(part, "endpoint=") {
            endpoint = strings.TrimPrefix(part, "endpoint=")
        }
        if strings.HasPrefix(part, "accesskey=") {
            accessKey = strings.TrimPrefix(part, "accesskey=")
        }
    }
    return endpoint, accessKey
}

Make sure to replace "***********" with your actual access key and adjust the payload according to your requirements. This code assumes that the access key is provided in plain text in the connection string for simplicity. In a real-world scenario, you'd want to handle the access key securely, possibly using environment variables or secret management tools.

This example assumes you will retain the existing connection string format.

Upvotes: 1

Related Questions