mysql - 不能将通知(类型 []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"`
}
解决方案
编写一个循环以从通知中提取电子邮件地址作为字符串片段:
addresses := make([]string, len(notifs))
for i, notif := range notifs {
addresses[i] = notif.Email
}
使用切片设置标题:
mailer.SetHeader("To", addresses...)
推荐阅读
- javascript - 无法从外部 html 文件获取元素到内容脚本
- gcloud - 从 json 文件创建 gcloud 配置
- c++ - 当我在 C++ 中的类中使用类时收到警告
- python - Python:为每个对象添加一个以唯一方式依赖于其他属性的数据类对象属性
- c# - ImageMagik 图片未正确渲染,图像上到处都是白色方块
- python - 如何在opencv中显示没有背景的手
- google-apps-script - Google 幻灯片中链接的 Google 表格
- php - 从 PHAR 文件对 tmp/ 进行读/写访问
- python - success_url django中的无类型对象
- node.js - Mongodb expressjs通过ref删除数组内的一个对象