This page looks best with JavaScript enabled

Sending emails from a script using a GMail account

 ·  🎃 kr0m

On several occasions, it is necessary to send emails from a server, either to alert about an event or to send some type of report. Normally, this is done by installing a local postfix and sending the email with the mail command, but this method has some drawbacks. If many emails are sent, the server’s IP will end up on some blacklist. We have an additional service running on our server, which implies in terms of consumed resources and security problems. The solution is to use an external GMail account.

We will use a small script in Go:

emerge -av dev-lang/go

We install the gomail library:

mkdir go
export GOPATH=/root/go
go get gopkg.in/gomail.v2

We program the script:

vi smtp-gmail-send.go

package main

import (
    "os"
    "strings"
    "crypto/tls"
    "gopkg.in/gomail.v2"
)

func main() {
    from := os.Args[1]
    toRaw := os.Args[2]
    pass := os.Args[3]
    subject := os.Args[4]
    body := os.Args[5]

    d := gomail.NewDialer("smtp.gmail.com", 587, from, pass)
    d.TLSConfig = &tls.Config{InsecureSkipVerify: true}

    m := gomail.NewMessage()
    m.SetHeader("From", from)
    m.SetHeader("Subject", subject)
    m.SetBody("text/html", body)

    toSplitted := strings.Split(toRaw, " ")
    for _,to := range toSplitted {
        m.SetHeader("To", to)
        if err := d.DialAndSend(m); err != nil {
            panic(err)
        }
    }
}

We run it first to check that it doesn’t give problems:

go run smtp-gmail-send.go USERNAME@gmail.com "DEST1@gmail.com DEST2@gmail.com" PASSWORD "testSubject: SUBJECT:SUBJECT" "BODY:BODY"

We compile it:

go build -o /bin/smtp-gmail-send smtp-gmail-send.go

I’m not an expert in Go by any means, so it can surely be improved. For example, sending emails to multiple recipients could be done in a single line without having to execute the loop.

If you liked the article, you can treat me to a RedBull here