當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO SendMail用法及代碼示例

GO語言"net/smtp"包中"SendMail"函數的用法及代碼示例。

用法:

func SendMail(addr string, a Auth, from string, to []string, msg []byte) error

SendMail 在 addr 連接到服務器,如果可能,切換到 TLS,如果可能,使用可選機製 a 進行身份驗證,然後從地址 from 到地址發送一封電子郵件,並帶有消息 msg。地址必須包括一個端口,如"mail.example.com:smtp"。

to 參數中的地址是 SMTP RCPT 地址。

msg 參數應該是 RFC 822 樣式的電子郵件,首先是標題,一個空行,然後是郵件正文。 msg 的行應該是 CRLF 終止的。 msg 標頭通常應包含"From"、"To"、"Subject" 和"Cc" 等字段。發送 "Bcc" 消息是通過在 to 參數中包含電子郵件地址但不包含在 msg 標頭中來完成的。

SendMail 函數和 net/smtp 包是低級機製,不支持 DKIM 簽名、MIME 附件(請參閱 mime/multipart 包)或其他郵件函數。更高級別的包存在於標準庫之外。

例子:

package main

import (
	"log"
	"net/smtp"
)

func main() {
	// Set up authentication information.
	auth := smtp.PlainAuth("", "user@example.com", "password", "mail.example.com")

	// Connect to the server, authenticate, set the sender and recipient,
	// and send the email all in one step.
	to := []string{"recipient@example.net"}
	msg := []byte("To: recipient@example.net\r\n" +
		"Subject: discount Gophers!\r\n" +
		"\r\n" +
		"This is the email body.\r\n")
	err := smtp.SendMail("mail.example.com:25", auth, "sender@example.org", to, msg)
	if err != nil {
		log.Fatal(err)
	}
}

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 SendMail。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。