首页 > 解决方案 > 如何通过 Gmail Go SDK 将 html 模板正文作为电子邮件发送?

问题描述

我创建了一个 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())
        }
    }
}

标签: gogoogle-apigmailgmail-api

解决方案


错误在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")
}

推荐阅读