github twitter
snippet: adding a contact to a mailjet list, using go
Aug 12, 2019
One minute read

This is a small snippet for a function that subscribes a contact to a list using Go and Mailjet, an email delivery and marketing platform.

Their api exposes a high end http client that allows you to build the requests that are going to be sent to their server. You can check the documentation guides here. There are official libraries for most programming languages, you can check their github page.

Assuming we have a form with the fields firstname, lastname and email:

func subscribe(listID int64, data map[string]string) ([]resources.ContactManagemanycontacts, error) {
    var ret []resources.ContactManagemanycontacts

    info := &mailjet.Request{
        Resource: "contact",
        Action:   "managemanycontacts",
    }

    payload := resources.ContactManagemanycontacts{
        ContactsLists: []resources.ContactsListAction{
            resources.ContactsListAction{
                Action: "addnoforce",
                ListID: listID,
            },
        },

        Contacts: []resources.AddContactAction{
            resources.AddContactAction{
                Name:  data["firstname"],
                Email: data["email"],
                Properties: struct {
                    FirstName string
                    LastName  string
                }{
                    FirstName: data["firstname"],
                    LastName:  data["lastname"],
                },
            },
        },
    }

    req := &mailjet.FullRequest{
        Info:    info,
        Payload: payload,
    }

    if err := m.Post(fmr, &ret); err != nil {
        return nil, err
    }

    return ret, nil
}

Back to posts