golang 使用 azure 通信服务发送电子邮件

问题描述 投票:0回答:1

我有一个用于发送电子邮件的天蓝色通信服务模板。 我们的项目是在golang中,我需要实现一种基于azure通信服务发送电子邮件的方法。 我找到了 karim-w 库,但对我不起作用,而且很复杂。

我在 python 中实现了这段代码,它工作正常。 我也想在 golang 中实现这个。

有什么想法或建议吗?

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()

提前致谢

azure go email goland azure-communication-services
1个回答
0
投票

试试这个:

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/Azure/azure-sdk-for-go/services/communication/email"
    "github.com/Azure/go-autorest/autorest"
)

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

    // Create an EmailClient using the connection string
    client := email.NewEmailClient(connectionString)

    // Define the email message
    message := email.Email{
        From: &email.EmailAddress{
            Address: "[email protected]",
        },
        To: []email.EmailRecipient{
            {
                EmailAddress: email.EmailAddress{
                    Address: "[email protected]",
                },
            },
        },
        Subject: "Test Email",
        Content: &email.EmailContent{
            PlainTextContent: "Hello world via email.",
        },
    }

    // Send the email
    resp, err := client.Send(context.Background(), message)
    if err != nil {
        log.Fatalf("Failed to send email: %v", err)
    }

    if resp.StatusCode != 202 {
        log.Fatalf("Unexpected status code: %d", resp.StatusCode)
    }

    fmt.Println("Email sent successfully!")
}

确保已安装 Azure SDK for Go。

© www.soinside.com 2019 - 2024. All rights reserved.