go语言实现给多人发送邮件
时间: 2024-04-24 18:23:23 浏览: 10
你可以使用 Go 语言的标准库 `net/smtp` 来实现给多人发送邮件。下面是一个简单的示例代码:
```go
package main
import (
"fmt"
"log"
"net/smtp"
)
func main() {
// 配置 SMTP 服务器信息
smtpHost := "smtp.example.com"
smtpPort := 587
username := "your_username"
password := "your_password"
// 构建邮件内容
from := "sender@example.com"
to := []string{"recipient1@example.com", "recipient2@example.com"}
subject := "Hello, World!"
body := "This is the email body."
message := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s", from, to, subject, body)
// 连接到 SMTP 服务器
auth := smtp.PlainAuth("", username, password, smtpHost)
conn, err := smtp.Dial(fmt.Sprintf("%s:%d", smtpHost, smtpPort))
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// 执行身份验证
if err = conn.Auth(auth); err != nil {
log.Fatal(err)
}
// 设置寄件人和收件人
if err = conn.Mail(from); err != nil {
log.Fatal(err)
}
for _, recipient := range to {
if err = conn.Rcpt(recipient); err != nil {
log.Fatal(err)
}
}
// 发送邮件内容
dataWriter, err := conn.Data()
if err != nil {
log.Fatal(err)
}
defer dataWriter.Close()
_, err = fmt.Fprintf(dataWriter, message)
if err != nil {
log.Fatal(err)
}
log.Println("Email sent successfully!")
}
```
请注意替换代码中的 SMTP 服务器地址、端口、用户名、密码、发件人地址和收件人地址。这段代码会连接到指定的 SMTP 服务器,并发送邮件给多个收件人。