Отправка почты с Go и Postfix на localhost - PullRequest
0 голосов
/ 13 марта 2020

В моем приложении Go есть следующий код.

func sendMail(addr, from, subject, body string, to []string) error {
    r := strings.NewReplacer("\r\n", "", "\r", "", "\n", "", "%0a", "", "%0d", "")

    c, err := smtp.Dial(addr)
    if err != nil {
        return err
    }
    defer c.Close()
    if err = c.Mail(r.Replace(from)); err != nil {
        return err
    }
    for i := range to {
        to[i] = r.Replace(to[i])
        if err = c.Rcpt(to[i]); err != nil {
            return err
        }
    }

    w, err := c.Data()
    if err != nil {
        return err
    }

    msg := "To: " + strings.Join(to, ",") + "\r\n" +
        "From: " + from + "\r\n" +
        "Subject: " + subject + "\r\n" +
        "Content-Type: text/html; charset=\"UTF-8\"\r\n" +
        "Content-Transfer-Encoding: base64\r\n" +
        "\r\n" + base64.StdEncoding.EncodeToString([]byte(body))

    _, err = w.Write([]byte(msg))
    if err != nil {
        return err
    }
    err = w.Close()
    if err != nil {
        return err
    }
    return c.Quit()
}

, который я нашел здесь на SO. Тогда у меня есть этот вызов в моем коде:

if err := sendMail("127.0.0.1:25", "SENDER", "Subject", body, []string{sendNewPassword.Email}); err != nil {
        log.Println(err.Error())
        w.WriteHeader(http.StatusBadRequest)
        return
    }

Дело в том, что я не получаю никаких ошибок в своих журналах, но почта никогда не приходит. И когда я вижу почтовый журнал на sudo cat /var/log/mail.log, там ничего не значится. Даже не предупреждения.

Еще одна вещь, на которую стоит обратить внимание, - это то, что я могу отправлять почту с помощью стандартных инструментов. Например: cat "Некоторый текст" | mailx -s 'Test mail' myemail@gmail.com Работает отлично. Это мой main.cf для постфикса:

[~]@Ubuntu1910 #> cat /etc/postfix/main.cf
# See /usr/share/postfix/main.cf.dist for a commented, more complete version


# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# See http://www.postfix.org/COMPATIBILITY_README.html -- default to 2 on
# fresh installs.
compatibility_level = 2



# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = Ubuntu1910
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
mydestination = $myhostname, Ubuntu1910, localhost.localdomain, , localhost
relayhost = 
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = loopback-only 
inet_protocols = all

Может кто-то увидеть что-то не так с моим конфигом? (или мой код)

Редактировать: Кстати, это тоже не получается:

curl --url 'smtps://localhost:25' --ssl-reqd --mail-from 'username@gmail.com' --mail-rcpt 'myemail@gmail.com' --upload-file mail.txt --insecure

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number
...