サーチ…


構文

  • func PlainAuth(アイデンティティ、ユーザー名、パスワード、ホスト文字列)認証
  • func SendMail(addr文字列、Auth、文字列から、[]文字列、msg [] byte)エラー

smtp.SendMail()でメールを送信する

電子メールを送信するのは、Goでは非常に簡単です。電子メールが必要とするスタイルを指定するRFC 822を理解するのに役立ちます。以下のコードは、RFC 822準拠の電子メールを送信します。

package main

import (
    "fmt"
    "net/smtp"
)

func main() {
    // user we are authorizing as
    from := "[email protected]"

    // use we are sending email to
    to := "[email protected]"

    // server we are authorized to send email through
    host := "mail.example.com"

    // Create the authentication for the SendMail()
    // using PlainText, but other authentication methods are encouraged
    auth := smtp.PlainAuth("", from, "password", host)

    // NOTE: Using the backtick here ` works like a heredoc, which is why all the 
    // rest of the lines are forced to the beginning of the line, otherwise the 
    // formatting is wrong for the RFC 822 style
    message := `To: "Some User" <[email protected]>
From: "Other User" <[email protected]>
Subject: Testing Email From Go!!

This is the message we are sending. That's it!
`

    if err := smtp.SendMail(host+":25", auth, from, []string{to}, []byte(message)); err != nil {
        fmt.Println("Error SendMail: ", err)
        os.Exit(1)
    }
    fmt.Println("Email Sent!")
}

上記は、次のようなメッセージを送信します:

To: "Other User" <[email protected]>
From: "Some User" <[email protected]>
Subject: Testing Email From Go!!

This is the message we are sending. That's it!
.


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow