Bulk Mailer Example
In this example we create a small bulk mailer for sending out the same mail to a bigger list of
recipients. It is important for us to address the recipient directly in the mail, therefore we
will make use of Go’s html/template
and text/template
system together with placeholders.
|
|
Let’s take the example apart to look at some details…
At first, in line 15, we define a new type for our users that we want to address. This is totally optional and is only done so we can easily work with a list of users and address them later on in our text template. How you handle this, is totally up to you and not mandatory for this to work.
In line 28 thru 48 we set up a simple text and HTML template mail body with placeholders
that can be used with Go’s html/template
and text/template
.
Next we set up a list of users, we want to send our great bulk mailing to. Line 52 uses the User
type for this. With the preparation work done, we will start looping over all of our users in line 70.
For each user we create a new *mail.Msg
.
For bulk mailings it is common that the ENVELOPE FROM
and the MAIL FROM
differ, so that bounce mails are sent
to some system that can mark those bounces in the local system as bounced. Therefore we set both of those from
addresses in line 73 and line 76. The lines 79 to 85 should be
of no surprise to you, if you already used go-mail before.
One more interesting thing happens in lines 86 thru 91 in which we use our
prepared html/template
and text/template
templates and apply it to our mail message using
m.SetBodyHTMLTemplate
and m.AddAlternativeTextTemplate
. We provide the whole user struct as data to that
methods, so that html/template
and text/template
can take care of replacing placeholders in the mail body.
Go-mail will take care of all the bells and whistles with the template handling for you. With our mail message
now complete, we append it to our mail message slice in line 93.
Finally we create a new Client and send out all of our prepared messages in one go by
providing the whole slice of messages to Client.DialAndSend
.