Skip to content

Instantly share code, notes, and snippets.

@tmichel
Created October 12, 2014 11:58
Show Gist options
  • Select an option

  • Save tmichel/a57bd4033db3e90f5516 to your computer and use it in GitHub Desktop.

Select an option

Save tmichel/a57bd4033db3e90f5516 to your computer and use it in GitHub Desktop.
Sending and testing email in Go -- appendix
package email
import (
"net/smtp"
"testing"
)
type EmailConfig struct {
Username string
Password string
ServerHost string
ServerPort string
SenderAddr string
}
type EmailSender interface {
Send(to []string, body []byte) error
}
func NewEmailSender(conf EmailConfig) EmailSender {
return &emailSender{conf, smtp.SendMail}
}
type emailSender struct {
conf EmailConfig
send func(string, smtp.Auth, string, []string, []byte) error
}
func (e *emailSender) Send(to []string, body []byte) error {
addr := e.conf.ServerHost + ":" + e.conf.ServerPort
auth := smtp.PlainAuth("", e.conf.Username, e.conf.Password, e.conf.ServerHost)
return e.send(addr, auth, e.conf.SenderAddr, to, body)
}
/****** testing ******/
func TestEmail_SendSuccessful(t *testing.T) {
f, r := mockSend(nil)
sender := &emailSender{send: f}
body := "Hello World"
err := sender.Send([]string{"me@example.com"}, []byte(body))
if err != nil {
t.Errorf("unexpected error: %s", err)
}
if string(r.msg) != body {
t.Errorf("wrong message body.\n\nexpected: %\n got: %s", body, r.msg)
}
}
func mockSend(errToReturn error) (func(string, smtp.Auth, string, []string, []byte) error, *emailRecorder) {
r := new(emailRecorder)
return func(addr string, a smtp.Auth, from string, to []string, msg []byte) error {
*r = emailRecorder{addr, a, from, to, msg}
return errToReturn
}, r
}
type emailRecorder struct {
addr string
auth smtp.Auth
from string
to []string
msg []byte
}
@vaishakhvm
Copy link
Copy Markdown

where we need to provide with the user id and password in the above code. also can we directly give the base URL to login

@AGMETEOR
Copy link
Copy Markdown

AGMETEOR commented Mar 4, 2021

Amazing! Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment