Last active
June 9, 2023 21:56
-
-
Save hitoshiichikawa/fa10ac6540cb97c3ef5d65451afd64e3 to your computer and use it in GitHub Desktop.
sendgridSMTPでメール送るサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//sendgridsmtpsample.go | |
//SMTPでsendgrid使うサンプル | |
//環境変数必要 | |
//SMTP_USER SMTP認証のユーザー名 | |
//SMTP_PASSWORD SMTP認証のパスワード | |
package main | |
import ( | |
"fmt" | |
mail "github.com/xhit/go-simple-mail/v2" | |
"log" | |
"os" | |
"time" | |
) | |
func usage() { | |
fmt.Print("sendgridsmtpsample <FROM> <TO>") | |
} | |
func main() { | |
//引数の確認 | |
if len(os.Args) != 3 { | |
usage() | |
return | |
} | |
//引数からのアドレス取り出し | |
from := os.Args[1] | |
to := os.Args[2] | |
//メールサーバオブジェクトの準備 | |
mailserver := mail.NewSMTPClient() | |
//STARTTLSで暗号化、PORTは587 | |
mailserver.Host = "smtp.sendgrid.net" | |
mailserver.Port = 587 | |
mailserver.Encryption = mail.EncryptionSTARTTLS | |
mailserver.Username = os.Getenv("SMTP_USER") | |
mailserver.Password = os.Getenv("SMTP_PASSWORD") | |
mailserver.Authentication = mail.AuthLogin | |
mailserver.KeepAlive = true | |
mailserver.ConnectTimeout = 300 * time.Second | |
mailserver.SendTimeout = 300 * time.Second | |
smtpClient, err := mailserver.Connect() | |
if err != nil { | |
log.Fatal(err) | |
return | |
} | |
//メールオブジェクトの準備 | |
email := mail.NewMSG() | |
email.SetFrom(from) | |
email.AddTo(to) | |
email.SetSubject("test mail") | |
email.SetBody(mail.TextPlain, "test mail") | |
//送信 | |
err = email.Send(smtpClient) | |
if err != nil { | |
log.Fatal(err) | |
return | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment