首页 > 解决方案 > 不能将通知(类型 []entity.Notif 的变量)用作数组或切片文字中的字符串值(已解决)

问题描述

如何解决这个问题?我想从数据库中获取电子邮件数据以发送包含该数据的电子邮件。此代码来自controller/notif-controller.go

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")

    notifs := c.notifService.EmailByDiv(email_to)

    to := []string{notifs}

    mailer := gomail.NewMessage()
    mailer.SetHeader("From", CONFIG_SENDER_NAME)
    mailer.SetHeader("To", to)
    mailer.SetHeader("Cc", cc_to)
    mailer.SetHeader("Subject", subject)
    mailer.SetBody("text/html", body)

    // dialer := &gomail.Dialer{Host: CONFIG_SMTP_HOST, Port: CONFIG_SMTP_PORT}
    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!")
}

我有错误:

不能将通知([]entity.Notif 类型的变量)用作数组或切片文字中的字符串值,也不能将 to([] 字符串类型的变量)用作 mailer.SetHeader 参数中的字符串值

我添加了一个循环,它是这样的:

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)

    to := []string{notifs}

    mailer := gomail.NewMessage()

    addresses := make([]string, len(to))
    for i, recipient := range to {
        addresses[i] = mailer.FormatAddress(recipient, "")
    }

    mailer.SetHeader("From", CONFIG_SENDER_NAME)
    mailer.SetHeader("To", addresses...)
    mailer.SetHeader("Cc", cc_to)
    mailer.SetHeader("Subject", subject)
    mailer.SetBody("text/html", body)
    // mailer.Attach(file)

    // dialer := &gomail.Dialer{Host: CONFIG_SMTP_HOST, Port: CONFIG_SMTP_PORT}
    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!")
}

我有这样的错误:

不能将通知([]entity.Notif 类型的变量)用作数组或切片文字中的字符串值

来自entity/notif.go的 entity.Notif 文件包含:

package entity

type Notif struct {
    Email string `gorm:"type:varchar(255)" json:"email"`
}

标签: mysqlgo

解决方案


编写一个循环以从通知中提取电子邮件地址作为字符串片段:

addresses := make([]string, len(notifs))
for i, notif := range notifs {
    addresses[i] = notif.Email
}

使用切片设置标题:

mailer.SetHeader("To", addresses...)

推荐阅读