postfix and golang - sending emails

A quick list of steps to get a server up and running with postfix and a go script to send emails.

Install postscript #

sudo apt-get install postscript

Select ‘local copy’ as the configuration and accept the defaults.

Configure postscript #

vim /etc/postfix/main.cf

Change the bottom from

inet_interfaces = loopback-only
default_transport = error
relay_transport = error
inet_protocols = all

to

inet_interfaces = all
inet_protocols = all

A go script to send emails #

package main

import (
    "fmt"
    "net/mail"
    "net/smtp"
    "strings"
)

var host = "127.0.0.1"
var port = "25"
var username = ""
var password = ""
var auth = smtp.PlainAuth("", username, password, host)
var addr = host + ":" + port

func main() {
    fromName := "Fred"
    fromEmail := "fred@example.com"
    toNames := []string{"Ted"}
    toEmails := []string{"ted@example.com"}
    subject := "This is the subject of your email"
    body := "This is the body of your email"
    // Build RFC-2822 email
    toAddresses := []string{}
    for i, _ := range toEmails {
        to := mail.Address{toNames[i], toEmails[i]}
        toAddresses = append(toAddresses, to.String())
    }
    toHeader := strings.Join(toAddresses, ", ")
    from := mail.Address{fromName, fromEmail}
    fromHeader := from.String()
    subjectHeader := subject
    header := make(map[string]string)
    header["To"] = toHeader
    header["From"] = fromHeader
    header["Subject"] = subjectHeader
    header["Content-Type"] = `text/html; charset="UTF-8"`
    msg := ""
    for k, v := range header {
        msg += fmt.Sprintf("%s: %s\r\n", k, v)
    }
    msg += "\r\n" + body
    bMsg := []byte(msg)
    // Send using local postfix service
    c, err := smtp.Dial(addr)
    if err != nil {
        return
    }
    defer c.Close()
    if err = c.Mail(fromHeader); err != nil {
        return
    }
    for _, addr := range toEmails {
        if err = c.Rcpt(addr); err != nil {
            return
        }
    }
    w, err := c.Data()
    if err != nil {
        return
    }
    _, err = w.Write(bMsg)
    if err != nil {
        return
    }
    err = w.Close()
    if err != nil {
        return
    }
    err = c.Quit()
    // Or alternatively, send with remote service like Amazon SES
    // err = smtp.SendMail(addr, auth, fromEmail, toEmails, bMsg)
    // Handle response from local postfix or remote service
    if err != nil {
        return
    }
}
 
40
Kudos
 
40
Kudos

Now read this

Debian on Kobo Mini

Installation instructions at https://sites.google.com/site/gibekm/hardware/kobo/kobo-as-tablet General discussions that provided a lot of the info in this post are at http://www.mobileread.com/forums/showthread.php?t=220350 and... Continue →