LoginSignup
4
7

More than 3 years have passed since last update.

GMail APIでメール送信(Golang)

Last updated at Posted at 2018-07-11

GolangでGMail APIを利用し、メールを送信するサンプルを作ってみました。

以下のソースを実行すると、、
GMail APIを取得したGMailアカウントから
to@example.jpにメールを送信します。


package main

import (
    "fmt"
    "log"
    "strings"
    "time"

    "encoding/base64"
    "golang.org/x/oauth2"
    "golang.org/x/oauth2/google"
    "google.golang.org/api/gmail/v1"
)

func main() {

    config := oauth2.Config{
        ClientID:     "Your Client ID",
        ClientSecret: "Your Client Secret",
        Endpoint:     google.Endpoint,
        RedirectURL:  "urn:ietf:wg:oauth:2.0:oob",
        Scopes:       []string{"https://mail.google.com/"},
    }

    expiry, _ := time.Parse("2006-01-02", "2017-07-11")
    token := oauth2.Token{
        AccessToken:  "Your Access Token",
        TokenType:    "Bearer",
        RefreshToken: "Your Refresh Token",
        Expiry:       expiry,
    }

    client := config.Client(oauth2.NoContext, &token)

    srv, err := gmail.New(client)
    if err != nil {
        log.Fatalf("Unable to retrieve gmail Client %v", err)
    }

    temp := []byte("From: 'me'\r\n" +
        "reply-to: reply-to@example.jp\r\n" +
        "To: to@example.jp\r\n" +
        "Subject: TestSubject\r\n" +
        "\r\n" + "TestBody")

    var message gmail.Message
    message.Raw = base64.StdEncoding.EncodeToString(temp)
    message.Raw = strings.Replace(message.Raw, "/", "_", -1)
    message.Raw = strings.Replace(message.Raw, "+", "-", -1)
    message.Raw = strings.Replace(message.Raw, "=", "", -1)

    _, err = srv.Users.Messages.Send("me", &message).Do()
    if err != nil {
        fmt.Printf("%v", err)
    }
}

参考にしたもの:

以下を参考に、GMail APIを作成し、GolangでGMailのラベルを取得するサンプルを実装
http://takaya030.hatenablog.com/entry/2017/07/12/002841

以下を参考に、GMail APIでメールを送信する処理を実装
https://stackoverflow.com/questions/37523884/send-email-with-attachment-using-gmail-api-in-golang

4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7