diff options
author | Unknwon <u@gogs.io> | 2017-04-04 19:29:59 -0400 |
---|---|---|
committer | Unknwon <u@gogs.io> | 2017-04-04 19:29:59 -0400 |
commit | d05395fe906dad7741201faa69a54fef538deda9 (patch) | |
tree | 11dae6c5c9b40b8ce85c7294bd0309c03cb1199e /pkg/mailer | |
parent | 37b10666dea98cebf75d0c6f11ee87211ef94703 (diff) |
Refactoring: rename modules -> pkg
Reasons to change:
1. Shorter than 'modules'
2. More generally used by other Go projects
3. Corresponds to the naming of '$GOPATH/pkg' directory
Diffstat (limited to 'pkg/mailer')
-rw-r--r-- | pkg/mailer/mail.go | 205 | ||||
-rw-r--r-- | pkg/mailer/mailer.go | 229 |
2 files changed, 434 insertions, 0 deletions
diff --git a/pkg/mailer/mail.go b/pkg/mailer/mail.go new file mode 100644 index 00000000..20e2b309 --- /dev/null +++ b/pkg/mailer/mail.go @@ -0,0 +1,205 @@ +// Copyright 2016 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package mailer + +import ( + "fmt" + "html/template" + + log "gopkg.in/clog.v1" + "gopkg.in/gomail.v2" + "gopkg.in/macaron.v1" + + "github.com/gogits/gogs/pkg/base" + "github.com/gogits/gogs/pkg/markup" + "github.com/gogits/gogs/pkg/setting" +) + +const ( + MAIL_AUTH_ACTIVATE base.TplName = "auth/activate" + MAIL_AUTH_ACTIVATE_EMAIL base.TplName = "auth/activate_email" + MAIL_AUTH_RESET_PASSWORD base.TplName = "auth/reset_passwd" + MAIL_AUTH_REGISTER_NOTIFY base.TplName = "auth/register_notify" + + MAIL_ISSUE_COMMENT base.TplName = "issue/comment" + MAIL_ISSUE_MENTION base.TplName = "issue/mention" + + MAIL_NOTIFY_COLLABORATOR base.TplName = "notify/collaborator" +) + +type MailRender interface { + HTMLString(string, interface{}, ...macaron.HTMLOptions) (string, error) +} + +var mailRender MailRender + +func InitMailRender(dir, appendDir string, funcMap []template.FuncMap) { + opt := &macaron.RenderOptions{ + Directory: dir, + AppendDirectories: []string{appendDir}, + Funcs: funcMap, + Extensions: []string{".tmpl", ".html"}, + } + ts := macaron.NewTemplateSet() + ts.Set(macaron.DEFAULT_TPL_SET_NAME, opt) + + mailRender = &macaron.TplRender{ + TemplateSet: ts, + Opt: opt, + } +} + +func SendTestMail(email string) error { + return gomail.Send(&Sender{}, NewMessage([]string{email}, "Gogs Test Email!", "Gogs Test Email!").Message) +} + +/* + Setup interfaces of used methods in mail to avoid cycle import. +*/ + +type User interface { + ID() int64 + DisplayName() string + Email() string + GenerateActivateCode() string + GenerateEmailActivateCode(string) string +} + +type Repository interface { + FullName() string + HTMLURL() string + ComposeMetas() map[string]string +} + +type Issue interface { + MailSubject() string + Content() string + HTMLURL() string +} + +func SendUserMail(c *macaron.Context, u User, tpl base.TplName, code, subject, info string) { + data := map[string]interface{}{ + "Username": u.DisplayName(), + "ActiveCodeLives": setting.Service.ActiveCodeLives / 60, + "ResetPwdCodeLives": setting.Service.ResetPwdCodeLives / 60, + "Code": code, + } + body, err := mailRender.HTMLString(string(tpl), data) + if err != nil { + log.Error(3, "HTMLString: %v", err) + return + } + + msg := NewMessage([]string{u.Email()}, subject, body) + msg.Info = fmt.Sprintf("UID: %d, %s", u.ID(), info) + + SendAsync(msg) +} + +func SendActivateAccountMail(c *macaron.Context, u User) { + SendUserMail(c, u, MAIL_AUTH_ACTIVATE, u.GenerateActivateCode(), c.Tr("mail.activate_account"), "activate account") +} + +func SendResetPasswordMail(c *macaron.Context, u User) { + SendUserMail(c, u, MAIL_AUTH_RESET_PASSWORD, u.GenerateActivateCode(), c.Tr("mail.reset_password"), "reset password") +} + +// SendActivateAccountMail sends confirmation email. +func SendActivateEmailMail(c *macaron.Context, u User, email string) { + data := map[string]interface{}{ + "Username": u.DisplayName(), + "ActiveCodeLives": setting.Service.ActiveCodeLives / 60, + "Code": u.GenerateEmailActivateCode(email), + "Email": email, + } + body, err := mailRender.HTMLString(string(MAIL_AUTH_ACTIVATE_EMAIL), data) + if err != nil { + log.Error(3, "HTMLString: %v", err) + return + } + + msg := NewMessage([]string{email}, c.Tr("mail.activate_email"), body) + msg.Info = fmt.Sprintf("UID: %d, activate email", u.ID()) + + SendAsync(msg) +} + +// SendRegisterNotifyMail triggers a notify e-mail by admin created a account. +func SendRegisterNotifyMail(c *macaron.Context, u User) { + data := map[string]interface{}{ + "Username": u.DisplayName(), + } + body, err := mailRender.HTMLString(string(MAIL_AUTH_REGISTER_NOTIFY), data) + if err != nil { + log.Error(3, "HTMLString: %v", err) + return + } + + msg := NewMessage([]string{u.Email()}, c.Tr("mail.register_notify"), body) + msg.Info = fmt.Sprintf("UID: %d, registration notify", u.ID()) + + SendAsync(msg) +} + +// SendCollaboratorMail sends mail notification to new collaborator. +func SendCollaboratorMail(u, doer User, repo Repository) { + subject := fmt.Sprintf("%s added you to %s", doer.DisplayName(), repo.FullName()) + + data := map[string]interface{}{ + "Subject": subject, + "RepoName": repo.FullName(), + "Link": repo.HTMLURL(), + } + body, err := mailRender.HTMLString(string(MAIL_NOTIFY_COLLABORATOR), data) + if err != nil { + log.Error(3, "HTMLString: %v", err) + return + } + + msg := NewMessage([]string{u.Email()}, subject, body) + msg.Info = fmt.Sprintf("UID: %d, add collaborator", u.ID()) + + SendAsync(msg) +} + +func composeTplData(subject, body, link string) map[string]interface{} { + data := make(map[string]interface{}, 10) + data["Subject"] = subject + data["Body"] = body + data["Link"] = link + return data +} + +func composeIssueMessage(issue Issue, repo Repository, doer User, tplName base.TplName, tos []string, info string) *Message { + subject := issue.MailSubject() + body := string(markup.RenderSpecialLink([]byte(issue.Content()), repo.HTMLURL(), repo.ComposeMetas())) + data := composeTplData(subject, body, issue.HTMLURL()) + data["Doer"] = doer + content, err := mailRender.HTMLString(string(tplName), data) + if err != nil { + log.Error(3, "HTMLString (%s): %v", tplName, err) + } + from := gomail.NewMessage().FormatAddress(setting.MailService.FromEmail, doer.DisplayName()) + msg := NewMessageFrom(tos, from, subject, content) + msg.Info = fmt.Sprintf("Subject: %s, %s", subject, info) + return msg +} + +// SendIssueCommentMail composes and sends issue comment emails to target receivers. +func SendIssueCommentMail(issue Issue, repo Repository, doer User, tos []string) { + if len(tos) == 0 { + return + } + + SendAsync(composeIssueMessage(issue, repo, doer, MAIL_ISSUE_COMMENT, tos, "issue comment")) +} + +// SendIssueMentionMail composes and sends issue mention emails to target receivers. +func SendIssueMentionMail(issue Issue, repo Repository, doer User, tos []string) { + if len(tos) == 0 { + return + } + SendAsync(composeIssueMessage(issue, repo, doer, MAIL_ISSUE_MENTION, tos, "issue mention")) +} diff --git a/pkg/mailer/mailer.go b/pkg/mailer/mailer.go new file mode 100644 index 00000000..4c0960d6 --- /dev/null +++ b/pkg/mailer/mailer.go @@ -0,0 +1,229 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package mailer + +import ( + "crypto/tls" + "fmt" + "io" + "net" + "net/smtp" + "os" + "strings" + "time" + + "github.com/jaytaylor/html2text" + log "gopkg.in/clog.v1" + "gopkg.in/gomail.v2" + + "github.com/gogits/gogs/pkg/setting" +) + +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, from, subject, htmlBody string) *Message { + log.Trace("NewMessageFrom (htmlBody):\n%s", htmlBody) + + msg := gomail.NewMessage() + msg.SetHeader("From", from) + msg.SetHeader("To", to...) + msg.SetHeader("Subject", subject) + msg.SetDateHeader("Date", time.Now()) + + contentType := "text/html" + body := htmlBody + if setting.MailService.UsePlainText { + plainBody, err := html2text.FromString(htmlBody) + if err != nil { + log.Error(2, "html2text.FromString: %v", err) + } else { + contentType = "text/plain" + body = plainBody + } + } + msg.SetBody(contentType, 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.From, subject, body) +} + +type loginAuth struct { + username, password string +} + +// SMTP AUTH LOGIN Auth Handler +func LoginAuth(username, password string) smtp.Auth { + return &loginAuth{username, password} +} + +func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) { + return "LOGIN", []byte{}, nil +} + +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("unknwon fromServer: %s", string(fromServer)) + } + } + return nil, nil +} + +type Sender struct { +} + +func (s *Sender) Send(from string, to []string, msg io.WriterTo) error { + opts := setting.MailService + + 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} + } + + conn, err := net.Dial("tcp", net.JoinHostPort(host, port)) + if err != nil { + return err + } + defer conn.Close() + + isSecureConn := false + // Start TLS directly if the port ends with 465 (SMTPS protocol) + if strings.HasSuffix(port, "465") { + conn = tls.Client(conn, tlsconfig) + isSecureConn = true + } + + client, err := smtp.NewClient(conn, host) + if err != nil { + return fmt.Errorf("NewClient: %v", err) + } + + if !opts.DisableHelo { + hostname := opts.HeloHostname + if len(hostname) == 0 { + hostname, err = os.Hostname() + if err != nil { + return err + } + } + + if err = client.Hello(hostname); err != nil { + return fmt.Errorf("Hello: %v", err) + } + } + + // If not using SMTPS, alway use STARTTLS if available + hasStartTLS, _ := client.Extension("STARTTLS") + if !isSecureConn && hasStartTLS { + if err = client.StartTLS(tlsconfig); err != nil { + return fmt.Errorf("StartTLS: %v", err) + } + } + + 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") { + // Patch for AUTH LOGIN + auth = LoginAuth(opts.User, opts.Passwd) + } + + if auth != nil { + if err = client.Auth(auth); err != nil { + return fmt.Errorf("Auth: %v", err) + } + } + } + + if err = client.Mail(from); err != nil { + return fmt.Errorf("Mail: %v", err) + } + + for _, rec := range to { + if err = client.Rcpt(rec); err != nil { + return fmt.Errorf("Rcpt: %v", err) + } + } + + w, err := client.Data() + if err != nil { + return fmt.Errorf("Data: %v", err) + } else if _, err = msg.WriteTo(w); err != nil { + return fmt.Errorf("WriteTo: %v", err) + } else if err = w.Close(); err != nil { + return fmt.Errorf("Close: %v", err) + } + + return client.Quit() +} + +func processMailQueue() { + sender := &Sender{} + + 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 { + log.Error(3, "Fail 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) + } + } + } +} + +var mailQueue chan *Message + +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 + } + + mailQueue = make(chan *Message, setting.MailService.QueueLength) + go processMailQueue() +} + +func SendAsync(msg *Message) { + go func() { + mailQueue <- msg + }() +} |