Go - Sending simultaneous emails through goroutines times out - connection reset by peer
<p>I have 50 goroutines that start with a channel. Then, the process forever loops reading 100 database records at a time and sleeping for 10 seconds in between database calls. As it loops through the 100 email records to send, it passes each record through the channel to one of the 50 worker goroutines, who then sends the email. The problem is, after it goes through about 1000 emails, I start getting errors like this:</p>

<p>gomail: could not send email 1: read tcp 10.2.30.25:56708->216.###.##.###:25: read: connection reset by peer</p>

<p>I have to send out about 50k emails per day. What do you recommend? Here's the main code that processes the email queue and passes each record to the worker through the channel:</p>

<pre><code>func main() {

    MaxWorkers := 50
    println("Creating: " + strconv.Itoa(MaxWorkers) + " workers..")
    batchChannel := make(chan EmailQueue.EmailQueueObj)

    for i := 0; i &lt; MaxWorkers; i++ {
        go startWorker(batchChannel)
    }

    for {
        println("Getting queue..")
        data, _ := EmailQueue.GetQueue() //returns 100 database records

        println("Reading through " + strconv.Itoa(len(data)) + " records..")
        for _, element := range data {
            batchChannel &lt;- element
        }

        time.Sleep(10 * time.Second)
    }
}


func startWorker(channel chan EmailQueue.EmailQueueObj) {
    var s gomail.SendCloser
    var err error
    open := false
    for obj := range channel {
        if !open {
            s, err = dialer.Dial()
            if err != nil {
                fmt.Println(err.Error())
                return
            } else {
                sendEmail(obj, &amp;s)
            }
        } else {
            sendEmail(obj, &amp;s)
        }
        open = true
    }
    s.Close()
}

func sendEmail(obj EmailQueue.EmailQueueObj, s *gomail.SendCloser) {

    m := gomail.NewMessage()
    m.SetHeader("From", "example@example.com")
    m.SetHeader("To", obj.Recipient)
    m.SetHeader("Subject", obj.Subject.String)
    m.SetBody("text/html", obj.HTML.String)

    // Send the email
    response := ""
    status := ""
    if err := gomail.Send(*s, m); err != nil {
        response = err.Error()
        status = "error"
    } else {
        response = "Email sent"
        status = "sent"
    }
    m.Reset()

    return
}
</code></pre>

<p>I am using the library <a href="https://github.com/go-gomail/gomail" rel="nofollow">gomail</a> to send the emails. I am open to anything, even a new library or method to send these emails. But, what I'm doing currently is not working. Any help is greatly appreciated!</p>