使用 SendGrid 的 Go 客户端库能同时给多个邮箱发吗
作者:互联网
是的,使用 SendGrid 的 Go 客户端库(
Go
sendgrid-go
)可以同时向多个邮箱发送邮件。有几种方法可以实现这一点,下面是常见的做法之一:
package main
import (
"fmt"
"log"
"github.com/sendgrid/sendgrid-go"
"github.com/sendgrid/sendgrid-go/helpers/mail"
)
func main() {
// 创建一个 SendGrid 客户端
apiKey := "YOUR_SENDGRID_API_KEY"
client := sendgrid.NewSendClient(apiKey)
// 创建邮件
from := mail.NewEmail("Example User", "example@example.com")
subject := "Sending with SendGrid is Fun"
// 创建邮件对象
m := mail.NewV3MailInit(from, subject)
// 设置内容
content := mail.NewContent("text/plain", "and easy to do anywhere, even with Go")
m.AddContent(content)
// 创建一个 Personalization 对象
personalization := mail.NewPersonalization()
// 添加多个收件人
recipients := []string{"recipient1@example.com", "recipient2@example.com", "recipient3@example.com"}
for _, email := range recipients {
personalization.AddTos(mail.NewEmail("", email))
}
// 将 Personalization 添加到邮件中
m.AddPersonalizations(personalization)
// 发送邮件
response, err := client.Send(m)
if err != nil {
log.Printf("Error sending email: %v\n", err)
return
}
// 打印响应
fmt.Printf("Response Status Code: %d\n", response.StatusCode)
fmt.Printf("Response Body: %s\n", response.Body)
fmt.Printf("Response Headers: %v\n", response.Headers)
}
Go
代码解析
- 创建邮件:第一个参数是发件人,第二个参数是主题。
- 添加内容:通过
m.AddContent(content)
将邮件内容添加到邮件中。 - 创建
Personalization
:使用mail.NewPersonalization()
创建一个新的Personalization
对象,并添加多个收件人。 - 发送邮件:最后,调用
client.Send(m)
发送邮件。
总结
通过这个示例代码,你可以正确地向多个收件人发送邮件。
标签: 来源: