almost 8 years ago

Go má na posielanie mailov package net/smtp. Posielanie cez tento package je jednoduché (a niektoré utilitky robia postup ešte jednoduchší) - tu je príklad z dokumentácie:

sendmail.go
package main

import (
    "log"
    "net/smtp"
)

func main() {
    // Set up authentication information.

    auth := smtp.PlainAuth("", "user@example.com", "password", "mail.example.com")

    // Connect to the server, authenticate, set the sender and recipient,

    // and send the email all in one step.

    to := []string{"recipient@example.net"}
    msg := []byte("To: recipient@example.net\r\n" +
        "Subject: discount Gophers!\r\n" +
        "\r\n" +
        "This is the email body.\r\n")
    err := smtp.SendMail("mail.example.com:25", auth, "sender@example.org", to, msg)
    if err != nil {
        log.Fatal(err)
    }
}

To ale funguje iba pri štandardne nainštalovaných serveroch. Firemné servery v lokálnych sieťach majú často vypnutú authentifikáciu, takže sa neposiela meno a heslo. To urobíte takto:

err := smtp.SendMail("mail.example.com:25", nil, "sender@example.org", to, msg)

Bežne ale aj narazíte na situáciu, keď sa používa TLS protokol a adresa servera je iná ako jeho certifikát alebo je tam iný problém s certifikátom. Vtedy sa musí vypnúť TLS kontrola. V ďalšom príklade je použitá knižnica go-gomail a vypnutie TLS kontroly:

mail_test.go
package utils

import (
    "crypto/tls"
    "gopkg.in/gomail.v2"
    "testing"
    "time"
)

func TestSendMail2(t *testing.T) {
    m := gomail.NewMessage()
    m.SetHeader("From", "rioFrom@example.com")
    m.SetHeader("To", "rioTo@example.com")
    m.SetHeader("Subject", "Hello! "+time.Now().Format(time.Stamp))
    m.SetBody("text/html", "Ahoj <b>Jano</b> a <i>Fero</i>!")

    d := gomail.Dialer{Host: "smtp.example.com", Port: 25, TLSConfig: &tls.Config{InsecureSkipVerify: true}}
    t.Log("TLS", d.TLSConfig)
    if err := d.DialAndSend(m); err != nil {
        panic(err)
    }
}
← QR a PDF Poznámky o packages →
 
comments powered by Disqus