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

时间:2019-03-28 09:19:07

标签: go google-api gmail gmail-api

我创建了一个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("xyz@gmail.com", "abc@ionosnetworks.com", "pqr@gmail.com", "", "", "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())
        }
    }
}

1 个答案:

答案 0 :(得分: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")
}