nikoksr / notify

A dead simple Go library for sending notifications to various messaging services.
MIT License
2.79k stars 203 forks source link

[add]mail support TLS port and add README.md for mail #690

Closed AboutSange closed 2 months ago

AboutSange commented 10 months ago

Description

  1. Add mail.SetTLS and mail.UnSetTLS functions
  2. add README.md for mail

Motivation and Context

It solved: When using SMTP port 465 (TLS port) to send mail, always return error "failed to send email: EOF". And this problem is mentioned in https://github.com/nikoksr/notify/issues/269#issuecomment-1115986601

How Has This Been Tested?

  1. run example code in README.md, and attempted to set smtpPort to 25, 465, 587 respectively, all send mail successfully
  2. I write notify/service/mail/mail_send_test.go, and cd notify/service/mail/, and run go test, it's all PASS
package mail

import (
    "context"
    "crypto/tls"
    "log"
    "testing"

    "github.com/stretchr/testify/assert"
)

func TestMail_SendPort25(t *testing.T) {
    t.Parallel()

    m := New("xxx@163.com", "smtp.163.com:25")
    assert.False(t, m.useTLS)
    assert.Nil(t, m.tlsConfig)

    m.AuthenticateSMTP("", "xxx@163.com", "xxx", "smtp.163.com")
    m.AddReceivers("xxx@qq.com")

    // send a test message.
    err := m.Send(context.Background(),
        "SMTP port 25",
        "The actual message - Hello, you awesome gophers! :)",
    )
    if err != nil {
        log.Println(err)
    }
}

func TestMail_SendPort465(t *testing.T) {
    t.Parallel()

    m := New("xxx@163.com", "smtp.163.com:465")
    assert.False(t, m.useTLS)
    assert.Nil(t, m.tlsConfig)

    m.AuthenticateSMTP("", "xxx@163.com", "xxx", "smtp.163.com")
    m.AddReceivers("xxx@qq.com")
    m.SetTLS(&tls.Config{ServerName: "smtp.163.com"})
    assert.True(t, m.useTLS)
    assert.NotNil(t, m.tlsConfig)

    // send a test message.
    err := m.Send(context.Background(),
        "SMTP port 465",
        "The actual message - Hello, you awesome gophers! :)",
    )
    if err != nil {
        log.Println(err)
    }
}

func TestMail_SendPort587(t *testing.T) {
    t.Parallel()

    m := New("xxx@163.com", "smtp.163.com:587")
    assert.False(t, m.useTLS)
    assert.Nil(t, m.tlsConfig)

    m.AuthenticateSMTP("", "xxx@163.com", "xxx", "smtp.163.com")
    m.AddReceivers("xxx@qq.com")
    m.SetTLS(&tls.Config{ServerName: "smtp.163.com"})
    assert.True(t, m.useTLS)
    assert.NotNil(t, m.tlsConfig)

    m.UnSetTLS()
    assert.False(t, m.useTLS)

    m.SetTLS(&tls.Config{ServerName: "smtp.163.com"})
    assert.True(t, m.useTLS)
    assert.NotNil(t, m.tlsConfig)

    // send a test message.
    err := m.Send(context.Background(),
        "SMTP port 587",
        "The actual message - Hello, you awesome gophers! :)",
    )
    if err != nil {
        log.Println(err)
    }
}

Screenshots / Output (if appropriate):

go test result: all PASS

image

all mail was send success

image

Types of changes

Checklist: