Golang 电子邮件正文的模板格式不正确

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

在 Go 中使用模板发送电子邮件的代码,以便将来如果需要更多变量并可供其他人查看,可以轻松修改模板。

package main

import (
    "bytes"
    "strings"
    "text/template"
    "net/smtp"
    "log"
)

type Email_struct struct {
    Status      string
    App         string
    Project     string
    TargetEnv   string
    AppVersion  string
    Url string
}

func SendmaiL(emailTo string, e Email_struct) bool {    
    from := "[email protected]"
    to := []string{
        emailTo,
    }

    var tmplFile = "email.tmpl"
    tmpl, err := template.New(tmplFile).ParseFiles(tmplFile)
    if err != nil {
        panic(err)
    }
    var tpl bytes.Buffer
    if err := tmpl.Execute(&tpl, e); err != nil {
        panic(err)
    }
    message := tpl.Bytes()
    log.Print(string(message[:])) // print

    // Sending email.
    errs := smtp.SendMail("mail.domain.com:25", nil, from, to, message) 
    if errs != nil {
        log.Println(errs)
        return false
    }
    return true
}

func main() {
    // nl := "\r"

    em := Email_struct{}
    em.Status = "Synced"
    app := "pipeline-gitops-notification-sit"
    em.App = app
    // em.Project = app + nl
    em.Project = app
    GitopsFolder := "gitops/sit"
    extractTargetEnv := strings.Split(GitopsFolder, "/") 
    // em.TargetEnv = extractTargetEnv[1] + nl
    em.TargetEnv = extractTargetEnv[1] 
    mes := "Manifest-63db30e: qa-0.0.110 by [email protected]"
    extractVersion1 := strings.Split(mes, "-")
    extractVersion2 := strings.Split(extractVersion1[2], ".")
    extractVersion3 := strings.Split(extractVersion2[2], " ")
    // em.AppVersion = extractVersion2[0]+"."+extractVersion2[1]+"."+extractVersion3[0]  + nl
    em.AppVersion = extractVersion2[0]+"."+extractVersion2[1]+"."+extractVersion3[0] 
    RepoUrl := "https://cd.toronto.ca:6443/devops/pipeline/gitops-notification.git"
    em.Url = RepoUrl

    success := SendmaiL("[email protected]", em) 
    if success {
        log.Println("Email SUCCESS to sent!")
    } else {
        log.Println("Email FAILED to send!")
    }

}

带有模板文件email.tmpl,

Subject: [{{ .Status }}] app {{ .App }} has been synced by argoCD

Project: {{ .Project }}
Target : {{ .TargetEnv }}
Version: {{ .AppVersion }}
URL: {{ .Url }}

Best regards,
Devops Team

所需的电子邮件正文应该是(主题没有问题),

Project: PPPPPPPPPPPPPPPPP
Target : TTTTTTTTTTTTTTTTT
Version: VVVVVVVVVVVVVVVVV
URL: UUUUUUUUUUUUUUUUUUUU

Best regards,
Devops Team

但它会走直线,

Project: PPPPPPPPPPPPPPPPP Target : TTTTTTTTTTTTTTTTT Version: VVVVVVVVVVVVVVVVV URL: UUUUUUUUUUUUUUUUUUUU

Best regards,
Devops Team

如果我启用 nl := " " 或 nl := " “或者两者兼而有之。输出将是,

Project: PPPPPPPPPPPPPPPPP

Target : TTTTTTTTTTTTTTTTT

Version: VVVVVVVVVVVVVVVVV

URL: UUUUUUUUUUUUUUUUUUUU

Best regards,
Devops Team

这不美观。

请帮忙。

谢谢, 瑞克

go sendmail go-templates
1个回答
0
投票

解决方案是将模板主体放一行,

Subject: [{{ .Status }}] app {{ .App }} has been synced by argoCD

{{ .BodyLines }}

Best regards,
Devops Team
© www.soinside.com 2019 - 2024. All rights reserved.