You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go gin+gomail发邮件报错:[]entity.Notif不能作为string类型使用

报错修复方案

错误根因

编译报错的核心原因是类型不匹配:

  • c.notifService.EmailByDiv()返回值是[]entity.Notif类型的结构体切片,每个元素包含Email字符串字段,不能直接将整个结构体切片赋值给[]string类型的变量
  • gomail的SetHeader设置收件人时,需要传入展开的字符串可变参数,不能直接传入未展开的切片变量

修复步骤

  1. 遍历notifs结构体切片,提取每个元素的Email字段,生成合法的收件人字符串切片
  2. 用提取后的邮箱切片生成格式化的收件人地址,替换原来错误的赋值逻辑
  3. 若抄送参数cc_to是逗号分隔的多个邮箱,也需要拆分后再传入SetHeader

修复后的完整代码如下:

import "strings" // 如需拆分抄送邮箱可引入该包

func (c *notifController) SendNotifEmail(context *gin.Context) {
    email_to := context.Query("sEmailByDiv")
    cc_to := context.Query("cc_to")
    subject := context.Query("subject")
    body := context.Query("body")
    // file := context.Query("file")

    notifs := c.notifService.EmailByDiv(email_to)

    // 提取所有Notif结构体中的Email字段,生成字符串切片
    var to []string
    for _, n := range notifs {
        to = append(to, n.Email)
    }

    mailer := gomail.NewMessage()

    // 生成格式化的收件人地址
    addresses := make([]string, len(to))
    for i, recipient := range to {
        addresses[i] = mailer.FormatAddress(recipient, "")
    }

    // 可选:如果cc_to是逗号分隔的多个抄送邮箱,可拆分后传入
    // var ccList []string
    // if cc_to != "" {
    //     ccList = strings.Split(cc_to, ",")
    // }

    mailer.SetHeader("From", CONFIG_SENDER_NAME)
    mailer.SetHeader("To", addresses...)
    // 拆分抄送列表时替换为下行代码
    // mailer.SetHeader("Cc", ccList...)
    mailer.SetHeader("Cc", cc_to)
    mailer.SetHeader("Subject", subject)
    mailer.SetBody("text/html", body)
    // mailer.Attach(file)

    dialer := gomail.NewDialer(
        CONFIG_SMTP_HOST,
        CONFIG_SMTP_PORT,
        CONFIG_AUTH_EMAIL,
        CONFIG_AUTH_PASSWORD,
    )

    err := dialer.DialAndSend(mailer)
    if err != nil {
        log.Fatal(err.Error())
    }
    log.Println("Mail sent!")
}

内容的提问来源于stack exchange,提问作者Tezza Fazar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 10:18:03