Daniele B
Daniele B

Reputation: 20442

How to send emails via G-suite from Google Cloud

How can you send an email in Go from the Google Cloud owner G-suite email account?

Is it possible to use the Google Cloud projectID existing authorizations, without specifying the Google account password inside the Go source files?

Upvotes: 1

Views: 1317

Answers (2)

Daniele B
Daniele B

Reputation: 20442

An even better way is to create API/OAuth2 credentials directly in Google Cloud. In this way you don't even have to specify the server IP addresses as a security measure:

https://medium.com/wesionary-team/sending-emails-with-go-golang-using-smtp-gmail-and-oauth2-185ee12ab306

Upvotes: 1

Daniele B
Daniele B

Reputation: 20442

I found the solution!

And it's very simple: instead of specifying the account password, you can restrict the connection to your server IP address.

1) Sign in to your Google Admin console (https://admin.google.com) using the G-suite administrator account

2) Click on Apps -> G Suite -> Gmail -> Advanced settings

3) At the bottom of the page, mouse over on SMTP Relay Service and click on "ADD ANOTHER"

4) As Allowed Sender select "Only addresses in my domain"

5) Check Only accept mail from the specified IP addresses and type your server IP address

6) Confirm by clicking on "ADD SETTING" and then "SAVE"



This is the Go code required to send an email:

from := "[email protected]"
to := "[email protected]"

msg := "From: " + from + "\n" +
    "To: " + to + "\n" +
    "Subject: Hello there\n\n" +
    "SOME TEXT"

err := smtp.SendMail("smtp-relay.gmail.com:587", nil,
    from, []string{to}, []byte(msg))

if err != nil {
    log.Printf("smtp error: %s", err)
}

Upvotes: 3

Related Questions