Search code examples
emailgogoogle-cloud-platformsmtpgoogle-workspace

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?


Solution

  • 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 := "myuser@mydomain.com"
    to := "mail@recipient.com"
    
    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)
    }