-
-
Notifications
You must be signed in to change notification settings - Fork 54
Getting started
go-mail requires a working Go installation. Currently we require at least Go 1.16, but since the Go team only maintains the last two releases, it is advised to use the latest Go release available on the Go Downloads page.
go-mail can be installed using the Go module installation mechanism via the go get
command.
To install the latest version of go-mail, enter your project folder and simply import the module by issuing the following command:
$ go get github.com/wneessen/go-mail
Please keep in mind, that go-mail is a package and not a standalone application. There will be no go-mail
application for you to execute.
go-mail consists of two main components. The Msg
type, which represents the mail message and the Client
type which takes care of the mail delivery via a SMTP service.
First let's create a new Msg
using the NewMsg()
method and assign a sender address as well as a recipient address.
package main
import (
"github.com/wneessen/go-mail"
"log"
)
func main() {
message := mail.NewMsg()
if err := message.From("[email protected]"); err != nil {
log.Fatalf("failed to set From address: %s", err)
}
if err := message.To("[email protected]"); err != nil {
log.Fatalf("failed to set To address: %s", err)
}
}
In this little code snippet, first and foremost we import go-mail into our project (see the import
statement). Next we create a new message using the mail.NewMsg()
method. In the following lines, we use the From()
and To()
methods to set the sender and recipient addresses for our Msg
. Since go-mail makes sure that you are providing valid mail addresses, we return an error
. This way we can make sure that the provided address is accepted by go-mail and will not cause problems later on.
Next we want to set a subject line for our message and fill the mail body with some content.
m.Subject("This is my first mail with go-mail!")
m.SetBodyString(mail.TypeTextPlain, "Do you like this mail? I certainly do!")
We use the Subject()
method to add a subject line to our Msg
and then use SetBodyString()
to set a simple string as our message body. The first argument for SetBodyString()
is a content type. In our example the mail.TypeTextPlain
basically represents a text/plain
content type - meaning a plain text mail body.
Socials: go-mail on Mastodon | #go-mail on Discord | #go-mail on Slack