0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo.git synced 2024-12-28 18:34:10 -05:00
forgejo/modules/mailer/mailer.go

307 lines
7.4 KiB
Go
Raw Normal View History

2014-03-19 07:27:27 -05:00
// Copyright 2014 The Gogs Authors. All rights reserved.
// Copyright 2017 The Gitea Authors. All rights reserved.
2014-03-19 07:27:27 -05:00
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package mailer
import (
"bytes"
"crypto/tls"
2014-03-19 07:27:27 -05:00
"fmt"
"io"
"net"
2014-03-19 07:27:27 -05:00
"net/smtp"
"os"
"os/exec"
2014-03-19 07:27:27 -05:00
"strings"
"time"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"github.com/jaytaylor/html2text"
"gopkg.in/gomail.v2"
2014-03-19 07:27:27 -05:00
)
2016-11-24 20:44:04 -05:00
// Message mail body and log info
type Message struct {
Info string // Message information for log purpose.
*gomail.Message
}
// NewMessageFrom creates new mail message object with custom From header.
func NewMessageFrom(to []string, fromDisplayName, fromAddress, subject, body string) *Message {
log.Trace("NewMessageFrom (body):\n%s", body)
msg := gomail.NewMessage()
msg.SetAddressHeader("From", fromAddress, fromDisplayName)
msg.SetHeader("To", to...)
if len(setting.MailService.SubjectPrefix) > 0 {
msg.SetHeader("Subject", setting.MailService.SubjectPrefix+" "+subject)
} else {
msg.SetHeader("Subject", subject)
}
msg.SetDateHeader("Date", time.Now())
msg.SetHeader("X-Auto-Response-Suppress", "All")
plainBody, err := html2text.FromString(body)
if err != nil || setting.MailService.SendAsPlainText {
2017-09-11 20:04:14 -05:00
if strings.Contains(base.TruncateString(body, 100), "<html>") {
log.Warn("Mail contains HTML but configured to send as plain text.")
}
msg.SetBody("text/plain", plainBody)
} else {
msg.SetBody("text/plain", plainBody)
msg.AddAlternative("text/html", body)
}
return &Message{
Message: msg,
}
}
// NewMessage creates new mail message object with default From header.
func NewMessage(to []string, subject, body string) *Message {
return NewMessageFrom(to, setting.MailService.FromName, setting.MailService.FromEmail, subject, body)
}
type loginAuth struct {
2015-08-20 06:12:55 -05:00
username, password string
}
2016-11-24 20:44:04 -05:00
// LoginAuth SMTP AUTH LOGIN Auth Handler
func LoginAuth(username, password string) smtp.Auth {
return &loginAuth{username, password}
}
2016-11-24 20:44:04 -05:00
// Start start SMTP login auth
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
return "LOGIN", []byte{}, nil
}
2016-11-24 20:44:04 -05:00
// Next next step of SMTP login auth
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if more {
switch string(fromServer) {
case "Username:":
return []byte(a.username), nil
case "Password:":
return []byte(a.password), nil
default:
return nil, fmt.Errorf("unknown fromServer: %s", string(fromServer))
}
}
return nil, nil
}
// Sender SMTP mail sender
type smtpSender struct {
2014-03-19 07:27:27 -05:00
}
2016-11-24 20:44:04 -05:00
// Send send email
func (s *smtpSender) Send(from string, to []string, msg io.WriterTo) error {
opts := setting.MailService
2014-03-19 20:05:48 -05:00
host, port, err := net.SplitHostPort(opts.Host)
if err != nil {
return err
}
tlsconfig := &tls.Config{
InsecureSkipVerify: opts.SkipVerify,
ServerName: host,
}
if opts.UseCertificate {
cert, err := tls.LoadX509KeyPair(opts.CertFile, opts.KeyFile)
if err != nil {
return err
}
tlsconfig.Certificates = []tls.Certificate{cert}
}
2014-12-19 00:24:17 -05:00
conn, err := net.Dial("tcp", net.JoinHostPort(host, port))
if err != nil {
return err
}
defer conn.Close()
isSecureConn := opts.IsTLSEnabled || (strings.HasSuffix(port, "465"))
// Start TLS directly if the port ends with 465 (SMTPS protocol)
if isSecureConn {
conn = tls.Client(conn, tlsconfig)
}
2014-12-19 00:24:17 -05:00
client, err := smtp.NewClient(conn, host)
if err != nil {
2015-12-19 02:44:34 -05:00
return fmt.Errorf("NewClient: %v", err)
}
if !opts.DisableHelo {
hostname := opts.HeloHostname
2015-07-03 01:08:18 -05:00
if len(hostname) == 0 {
hostname, err = os.Hostname()
if err != nil {
return err
}
}
2015-02-20 02:12:27 -05:00
2015-07-03 01:08:18 -05:00
if err = client.Hello(hostname); err != nil {
2015-12-19 02:44:34 -05:00
return fmt.Errorf("Hello: %v", err)
2015-07-03 01:08:18 -05:00
}
2015-02-20 02:12:27 -05:00
}
// If not using SMTPS, always use STARTTLS if available
2014-12-19 00:24:17 -05:00
hasStartTLS, _ := client.Extension("STARTTLS")
if !isSecureConn && hasStartTLS {
if err = client.StartTLS(tlsconfig); err != nil {
2015-12-19 02:44:34 -05:00
return fmt.Errorf("StartTLS: %v", err)
}
}
2014-12-19 00:24:17 -05:00
canAuth, options := client.Extension("AUTH")
if canAuth && len(opts.User) > 0 {
var auth smtp.Auth
if strings.Contains(options, "CRAM-MD5") {
auth = smtp.CRAMMD5Auth(opts.User, opts.Passwd)
} else if strings.Contains(options, "PLAIN") {
auth = smtp.PlainAuth("", opts.User, opts.Passwd, host)
} else if strings.Contains(options, "LOGIN") {
2015-08-20 06:12:55 -05:00
// Patch for AUTH LOGIN
auth = LoginAuth(opts.User, opts.Passwd)
}
if auth != nil {
if err = client.Auth(auth); err != nil {
2015-12-19 02:44:34 -05:00
return fmt.Errorf("Auth: %v", err)
}
}
}
if err = client.Mail(from); err != nil {
2015-12-19 02:44:34 -05:00
return fmt.Errorf("Mail: %v", err)
}
for _, rec := range to {
if err = client.Rcpt(rec); err != nil {
2015-12-19 02:44:34 -05:00
return fmt.Errorf("Rcpt: %v", err)
}
}
w, err := client.Data()
if err != nil {
2015-12-19 02:44:34 -05:00
return fmt.Errorf("Data: %v", err)
} else if _, err = msg.WriteTo(w); err != nil {
2015-12-19 02:44:34 -05:00
return fmt.Errorf("WriteTo: %v", err)
} else if err = w.Close(); err != nil {
2015-12-19 02:44:34 -05:00
return fmt.Errorf("Close: %v", err)
}
return client.Quit()
}
// Sender sendmail mail sender
type sendmailSender struct {
}
// Send send email
func (s *sendmailSender) Send(from string, to []string, msg io.WriterTo) error {
var err error
var closeError error
var waitError error
args := []string{"-F", from, "-i"}
args = append(args, setting.MailService.SendmailArgs...)
args = append(args, to...)
log.Trace("Sending with: %s %v", setting.MailService.SendmailPath, args)
cmd := exec.Command(setting.MailService.SendmailPath, args...)
pipe, err := cmd.StdinPipe()
if err != nil {
return err
}
if err = cmd.Start(); err != nil {
return err
}
_, err = msg.WriteTo(pipe)
2014-03-19 07:27:27 -05:00
// we MUST close the pipe or sendmail will hang waiting for more of the message
// Also we should wait on our sendmail command even if something fails
closeError = pipe.Close()
waitError = cmd.Wait()
if err != nil {
return err
} else if closeError != nil {
return closeError
} else {
return waitError
}
}
// Sender sendmail mail sender
type dummySender struct {
}
// Send send email
func (s *dummySender) Send(from string, to []string, msg io.WriterTo) error {
buf := bytes.Buffer{}
if _, err := msg.WriteTo(&buf); err != nil {
return err
}
log.Info("Mail From: %s To: %v Body: %s", from, to, buf.String())
return nil
}
func processMailQueue() {
for {
select {
case msg := <-mailQueue:
log.Trace("New e-mail sending request %s: %s", msg.GetHeader("To"), msg.Info)
if err := gomail.Send(Sender, msg.Message); err != nil {
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
2019-04-02 02:48:31 -05:00
log.Error("Failed to send emails %s: %s - %v", msg.GetHeader("To"), msg.Info, err)
} else {
log.Trace("E-mails sent %s: %s", msg.GetHeader("To"), msg.Info)
2014-03-19 07:27:27 -05:00
}
}
}
}
2014-03-19 07:27:27 -05:00
var mailQueue chan *Message
// Sender sender for sending mail synchronously
var Sender gomail.Sender
2016-11-24 20:44:04 -05:00
// NewContext start mail queue service
func NewContext() {
// Need to check if mailQueue is nil because in during reinstall (user had installed
// before but swithed install lock off), this function will be called again
// while mail queue is already processing tasks, and produces a race condition.
if setting.MailService == nil || mailQueue != nil {
return
2014-03-19 07:27:27 -05:00
}
switch setting.MailService.MailerType {
case "smtp":
Sender = &smtpSender{}
case "sendmail":
Sender = &sendmailSender{}
case "dummy":
Sender = &dummySender{}
}
mailQueue = make(chan *Message, setting.MailService.QueueLength)
go processMailQueue()
2014-03-19 07:27:27 -05:00
}
2016-11-24 20:44:04 -05:00
// SendAsync send mail asynchronous
2014-03-19 20:05:48 -05:00
func SendAsync(msg *Message) {
2014-03-19 07:27:27 -05:00
go func() {
2014-03-19 20:05:48 -05:00
mailQueue <- msg
2014-03-19 07:27:27 -05:00
}()
}