如何通过Gmail Go SDK将html模板化的正文作为电子邮件发送?

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

我创建了一个html文件(即email.html),最终将我作为我的电子邮件正文模板。我尝试了以下代码,但我的电子邮件正文是一个纯文本,其中包含我编写的所有html(email.html)。

你能通过查看代码来建议吗?哪里出错?

注意:模板分析和执行工作正常。

码:

package main

import (
    "encoding/base64"
    "fmt"
    "html/template"
)

func getMessageString(fromEmail, To, ReplyTo, CC, BCC, Subject, emailBody string) []byte {
    return []byte("Reply-To: " + ReplyTo + "\r\n" + "From: " + fromEmail + "\r\n" + "To: " + To + "\r\n" + "Cc: " + CC + "\r\n" + "Bcc: " + BCC + "\r\n" + "Subject: " + Subject + "\r\n\r\n" + "MIME-Version: 1.0\r\n" + "Content-Type: text/html; charset=\"utf-8\"\r\n" + emailBody + "\r\n\r\n")
}

func main() {
    t, tempErr := template.New("template.html").ParseFiles("template.html")
    if tempErr != nil {
        fmt.Println(tempErr.Error())
        return
    }

    execErr := t.Execute(buf, data)
    if execErr != nil {
        fmt.Println(execErr.Error())
    } else {
        messageStr := getMessageString("[email protected]", "[email protected]", "[email protected]", "", "", "Test Subject", buf.String())

        var message gmail.Message
        message.Raw = base64.URLEncoding.EncodeToString(messageStr)

        _, err = svc.Users.Messages.Send("me", &message).Do()
        if err != nil {
            fmt.Println(err.Error())
        }
    }
}
go google-api gmail gmail-api
1个回答
1
投票

错误发生在getMessageString函数中:

"Subject: " + Subject + "\r\n\r\n"

注意双\r\n序列,邮件服务器在双\r\n之后解析所有内容作为电子邮件内容。在你的情况下,它跳过了Content-Type标题。所以只需删除一个\r\n,结果代码应如下所示:

func getMessageString(fromEmail, To, ReplyTo, CC, BCC, Subject, emailBody string) []byte {
    return []byte("Reply-To: " + ReplyTo + "\r\n" + "From: " + fromEmail + "\r\n" + "To: " + To + "\r\n" + "Cc: " + CC + "\r\n" + "Bcc: " + BCC + "\r\n" + "Subject: " + Subject + "\r\n" + "MIME-Version: 1.0\r\n" + "Content-Type: text/html; charset=\"utf-8\"\r\n\r\n" + emailBody + "\r\n")
}
© www.soinside.com 2019 - 2024. All rights reserved.