要使用Golang发送邮件,你可以使用net/smtp包。以下是一个示例代码,演示如何使用个人QQ邮箱发送邮件:
package main
import (
"fmt"
"log"
"net/smtp"
)
func main() {
from := "your_email@qq.com" // 发件人邮箱地址
password := "your_password" // 发件人邮箱密码或授权码
to := "recipient@example.com" // 收件人邮箱地址
subject := "这是邮件的主题"
body := "这是邮件的内容"
msg := fmt.Sprintf("From: %s\r\n", from) +
fmt.Sprintf("To: %s\r\n", to) +
fmt.Sprintf("Subject: %s\r\n", subject) +
"\r\n" + body
err := sendMail("smtp.qq.com:587", from, password, []string{to}, []byte(msg))
if err != nil {
log.Fatal(err)
}
fmt.Println("邮件发送成功!")
}
func sendMail(addr string, from string, password string, to []string, msg []byte) error {
auth := smtp.PlainAuth("", from, password, "smtp.qq.com")
err := smtp.SendMail(addr, auth, from, to, msg)
return err
}
请注意,由于QQ邮箱开启了SMTP服务需要授权码才能登录,因此需要将password替换为你的QQ邮箱授权码。另外,请将from、to、subject和body替换为实际的值。
确保你已经安装了Golang,并导入了所需的包。运行以上代码后,它将使用你的个人QQ邮箱发送邮件给指定的收件人。
内容由零声教学AI助手提供,问题来源于学员提问




