Golang 发送电子邮件:使用 net/smtp 包
在 Go 语言中,可以使用 'net/smtp' 包来发送电子邮件。以下是一个简单的示例:
package main
import (
"log"
"net/smtp"
)
func main() {
// 邮箱配置
email := 'your-email@example.com'
password := 'your-password'
smtpServer := 'smtp.example.com'
smtpPort := '587'
// 邮件内容
from := email
to := 'recipient@example.com'
subject := 'Test Email'
body := 'This is a test email.'
// 构建认证信息
auth := smtp.PlainAuth("", email, password, smtpServer)
// 构建邮件内容
msg := []byte("To: " + to + "\r\n" +
"Subject: " + subject + "\r\n" +
"\r\n" +
body + "\r\n")
// 发送邮件
err := smtp.SendMail(smtpServer+":" + smtpPort, auth, from, []string{to}, msg)
if err != nil {
log.Fatal(err)
}
log.Println("Email sent successfully!")
}
在上面的示例中,你需要将 'email'、'password'、'smtpServer' 和 'smtpPort' 替换为你自己的邮箱配置信息。然后,你可以设置收件人的邮箱地址、邮件主题和内容。最后,调用 'smtp.SendMail' 函数来发送邮件。
需要注意的是, 'net/smtp' 包只提供了基本的 SMTP 功能。如果你需要发送附件、使用 HTML 格式等高级功能,你可能需要使用第三方包,如 'gomail' 或 'email'。这些包提供了更强大和易用的 API 来处理电子邮件。
原文地址: https://www.cveoy.top/t/topic/l7ZL 著作权归作者所有。请勿转载和采集!