diff options
author | Unknwon <u@gogs.io> | 2015-09-17 01:54:12 -0400 |
---|---|---|
committer | Unknwon <u@gogs.io> | 2015-09-17 01:54:12 -0400 |
commit | 373731f5e85566eb385e92f604e81232e3d6ba1a (patch) | |
tree | 83311e464adf24f3006030e27473086e43a11240 /modules/mailer | |
parent | e75fd2f783a413ae612e3e6110c912b3ecf9555d (diff) | |
download | gitea-373731f5e85566eb385e92f604e81232e3d6ba1a.tar.gz gitea-373731f5e85566eb385e92f604e81232e3d6ba1a.zip |
user gomail and new activate account email tpl
- #1496: fallback plain text
- #1002: add date header
- #913: fix encoding of header
Diffstat (limited to 'modules/mailer')
-rw-r--r-- | modules/mailer/mail.go | 126 | ||||
-rw-r--r-- | modules/mailer/mailer.go | 182 |
2 files changed, 96 insertions, 212 deletions
diff --git a/modules/mailer/mail.go b/modules/mailer/mail.go index 9a38b57d26..e1577a7ab1 100644 --- a/modules/mailer/mail.go +++ b/modules/mailer/mail.go @@ -5,12 +5,10 @@ package mailer import ( - "encoding/hex" "errors" "fmt" "path" - "github.com/Unknwon/com" "github.com/Unknwon/macaron" "github.com/gogits/gogs/models" @@ -20,26 +18,16 @@ import ( ) const ( - AUTH_ACTIVE base.TplName = "mail/auth/active" - AUTH_ACTIVATE_EMAIL base.TplName = "mail/auth/activate_email" AUTH_REGISTER_SUCCESS base.TplName = "mail/auth/register_success" + AUTH_ACTIVATE base.TplName = "mail/auth/activate" + AUTH_ACTIVATE_EMAIL base.TplName = "mail/auth/activate_email" AUTH_RESET_PASSWORD base.TplName = "mail/auth/reset_passwd" NOTIFY_COLLABORATOR base.TplName = "mail/notify/collaborator" NOTIFY_MENTION base.TplName = "mail/notify/mention" ) -// Create New mail message use MailFrom and MailUser -func NewMailMessageFrom(To []string, from, subject, body string) Message { - return NewHtmlMessage(To, from, subject, body) -} - -// Create New mail message use MailFrom and MailUser -func NewMailMessage(To []string, subject, body string) Message { - return NewMailMessageFrom(To, setting.MailService.From, subject, body) -} - -func GetMailTmplData(u *models.User) map[interface{}]interface{} { +func ComposeTplData(u *models.User) map[interface{}]interface{} { data := make(map[interface{}]interface{}, 10) data["AppName"] = setting.AppName data["AppVer"] = setting.AppVer @@ -52,95 +40,45 @@ func GetMailTmplData(u *models.User) map[interface{}]interface{} { return data } -// create a time limit code for user active -func CreateUserActiveCode(u *models.User, startInf interface{}) string { - minutes := setting.Service.ActiveCodeLives - data := com.ToStr(u.Id) + u.Email + u.LowerName + u.Passwd + u.Rands - code := base.CreateTimeLimitCode(data, minutes, startInf) - - // add tail hex username - code += hex.EncodeToString([]byte(u.LowerName)) - return code -} - -// create a time limit code for user active -func CreateUserEmailActivateCode(u *models.User, e *models.EmailAddress, startInf interface{}) string { - minutes := setting.Service.ActiveCodeLives - data := com.ToStr(u.Id) + e.Email + u.LowerName + u.Passwd + u.Rands - code := base.CreateTimeLimitCode(data, minutes, startInf) - - // add tail hex username - code += hex.EncodeToString([]byte(u.LowerName)) - return code -} - -// Send user register mail with active code -func SendRegisterMail(r macaron.Render, u *models.User) { - code := CreateUserActiveCode(u, nil) - subject := "Register success, Welcome" - - data := GetMailTmplData(u) - data["Code"] = code - body, err := r.HTMLString(string(AUTH_REGISTER_SUCCESS), data) - if err != nil { - log.Error(4, "mail.SendRegisterMail(fail to render): %v", err) - return - } - - msg := NewMailMessage([]string{u.Email}, subject, body) - msg.Info = fmt.Sprintf("UID: %d, send register mail", u.Id) - - SendAsync(&msg) -} - -// Send email verify active email. -func SendActiveMail(r macaron.Render, u *models.User) { - code := CreateUserActiveCode(u, nil) - - subject := "Verify your e-mail address" - - data := GetMailTmplData(u) - data["Code"] = code - body, err := r.HTMLString(string(AUTH_ACTIVE), data) +func SendActivateAccountMail(c *macaron.Context, u *models.User) { + data := ComposeTplData(u) + data["Code"] = u.GenerateActivateCode() + body, err := c.HTMLString(string(AUTH_ACTIVATE), data) if err != nil { - log.Error(4, "mail.SendActiveMail(fail to render): %v", err) + log.Error(4, "HTMLString: %v", err) return } - msg := NewMailMessage([]string{u.Email}, subject, body) - msg.Info = fmt.Sprintf("UID: %d, send active mail", u.Id) + msg := NewMessage([]string{u.Email}, c.Tr("mail.activate_account"), body) + msg.Info = fmt.Sprintf("UID: %d, activate account", u.Id) - SendAsync(&msg) + SendAsync(msg) } -// Send email to verify secondary email. -func SendActivateEmail(r macaron.Render, user *models.User, email *models.EmailAddress) { - code := CreateUserEmailActivateCode(user, email, nil) - - subject := "Verify your e-mail address" - - data := GetMailTmplData(user) - data["Code"] = code +// SendActivateAccountMail sends confirmation e-mail. +func SendActivateEmailMail(c *macaron.Context, u *models.User, email *models.EmailAddress) { + data := ComposeTplData(u) + data["Code"] = u.GenerateEmailActivateCode(email.Email) data["Email"] = email.Email - body, err := r.HTMLString(string(AUTH_ACTIVATE_EMAIL), data) + body, err := c.HTMLString(string(AUTH_ACTIVATE_EMAIL), data) if err != nil { - log.Error(4, "mail.SendActiveMail(fail to render): %v", err) + log.Error(4, "HTMLString: %v", err) return } - msg := NewMailMessage([]string{email.Email}, subject, body) - msg.Info = fmt.Sprintf("UID: %d, send activate email to %s", user.Id, email.Email) + msg := NewMessage([]string{email.Email}, c.Tr("mail.activate_email"), body) + msg.Info = fmt.Sprintf("UID: %d, activate email: %s", u.Id, email.Email) - SendAsync(&msg) + SendAsync(msg) } // Send reset password email. func SendResetPasswdMail(r macaron.Render, u *models.User) { - code := CreateUserActiveCode(u, nil) + code := u.GenerateActivateCode() subject := "Reset your password" - data := GetMailTmplData(u) + data := ComposeTplData(u) data["Code"] = code body, err := r.HTMLString(string(AUTH_RESET_PASSWORD), data) if err != nil { @@ -148,10 +86,10 @@ func SendResetPasswdMail(r macaron.Render, u *models.User) { return } - msg := NewMailMessage([]string{u.Email}, subject, body) + msg := NewMessage([]string{u.Email}, subject, body) msg.Info = fmt.Sprintf("UID: %d, send reset password email", u.Id) - SendAsync(&msg) + SendAsync(msg) } // SendIssueNotifyMail sends mail notification of all watchers of repository. @@ -182,9 +120,9 @@ func SendIssueNotifyMail(u, owner *models.User, repo *models.Repository, issue * content := fmt.Sprintf("%s<br>-<br> <a href=\"%s%s/%s/issues/%d\">View it on Gogs</a>.", base.RenderSpecialLink([]byte(issue.Content), owner.Name+"/"+repo.Name), setting.AppUrl, owner.Name, repo.Name, issue.Index) - msg := NewMailMessageFrom(tos, u.Email, subject, content) + msg := NewMessageFrom(tos, u.Email, subject, content) msg.Info = fmt.Sprintf("Subject: %s, send issue notify emails", subject) - SendAsync(&msg) + SendAsync(msg) return tos, nil } @@ -198,7 +136,7 @@ func SendIssueMentionMail(r macaron.Render, u, owner *models.User, subject := fmt.Sprintf("[%s] %s (#%d)", repo.Name, issue.Name, issue.Index) - data := GetMailTmplData(nil) + data := ComposeTplData(nil) data["IssueLink"] = fmt.Sprintf("%s/%s/issues/%d", owner.Name, repo.Name, issue.Index) data["Subject"] = subject @@ -207,9 +145,9 @@ func SendIssueMentionMail(r macaron.Render, u, owner *models.User, return fmt.Errorf("mail.SendIssueMentionMail(fail to render): %v", err) } - msg := NewMailMessageFrom(tos, u.Email, subject, body) + msg := NewMessageFrom(tos, u.Email, subject, body) msg.Info = fmt.Sprintf("Subject: %s, send issue mention emails", subject) - SendAsync(&msg) + SendAsync(msg) return nil } @@ -219,7 +157,7 @@ func SendCollaboratorMail(r macaron.Render, u, owner *models.User, subject := fmt.Sprintf("%s added you to %s", owner.Name, repo.Name) - data := GetMailTmplData(nil) + data := ComposeTplData(nil) data["RepoLink"] = path.Join(owner.Name, repo.Name) data["Subject"] = subject @@ -228,9 +166,9 @@ func SendCollaboratorMail(r macaron.Render, u, owner *models.User, return fmt.Errorf("mail.SendCollaboratorMail(fail to render): %v", err) } - msg := NewMailMessage([]string{u.Email}, subject, body) + msg := NewMessage([]string{u.Email}, subject, body) msg.Info = fmt.Sprintf("UID: %d, send register mail", u.Id) - SendAsync(&msg) + SendAsync(msg) return nil } diff --git a/modules/mailer/mailer.go b/modules/mailer/mailer.go index b877bdaa1a..4dbcf1180b 100644 --- a/modules/mailer/mailer.go +++ b/modules/mailer/mailer.go @@ -7,16 +7,44 @@ package mailer import ( "crypto/tls" "fmt" + "io" "net" - "net/mail" "net/smtp" "os" "strings" + "time" + + "gopkg.in/gomail.v2" "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/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, body string) *Message { + msg := gomail.NewMessage() + msg.SetHeader("From", from) + msg.SetHeader("To", to...) + msg.SetHeader("Subject", subject) + msg.SetDateHeader("Date", time.Now()) + msg.SetBody("text/plain", body) + 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.From, subject, body) +} + type loginAuth struct { username, password string } @@ -44,74 +72,24 @@ func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) { return nil, nil } -type Message struct { - To []string - From string - Subject string - ReplyTo string - Body string - Type string - Massive bool - Info string -} - -// create mail content -func (m Message) Content() string { - // set mail type - contentType := "text/plain; charset=UTF-8" - if m.Type == "html" { - contentType = "text/html; charset=UTF-8" - } - - // create mail content - content := "From: " + m.From + "\r\nReply-To: " + m.ReplyTo + "\r\nSubject: " + m.Subject + "\r\nContent-Type: " + contentType + "\r\n\r\n" + m.Body - return content +type Sender struct { } -var mailQueue chan *Message - -func NewContext() { - if setting.MailService == nil { - return - } - - mailQueue = make(chan *Message, setting.MailService.QueueLength) - go processMailQueue() -} - -func processMailQueue() { - for { - select { - case msg := <-mailQueue: - num, err := Send(msg) - tos := strings.Join(msg.To, ", ") - info := "" - if err != nil { - if len(msg.Info) > 0 { - info = ", info: " + msg.Info - } - log.Error(4, fmt.Sprintf("Async sent email %d succeed, not send emails: %s%s err: %s", num, tos, info, err)) - } else { - log.Trace(fmt.Sprintf("Async sent email %d succeed, sent emails: %s%s", num, tos, info)) - } - } - } -} +func (s *Sender) Send(from string, to []string, msg io.WriterTo) error { + opts := setting.MailService -// sendMail allows mail with self-signed certificates. -func sendMail(settings *setting.Mailer, recipients []string, msgContent []byte) error { - host, port, err := net.SplitHostPort(settings.Host) + host, port, err := net.SplitHostPort(opts.Host) if err != nil { return err } tlsconfig := &tls.Config{ - InsecureSkipVerify: settings.SkipVerify, + InsecureSkipVerify: opts.SkipVerify, ServerName: host, } - if settings.UseCertificate { - cert, err := tls.LoadX509KeyPair(settings.CertFile, settings.KeyFile) + if opts.UseCertificate { + cert, err := tls.LoadX509KeyPair(opts.CertFile, opts.KeyFile) if err != nil { return err } @@ -159,17 +137,16 @@ func sendMail(settings *setting.Mailer, recipients []string, msgContent []byte) } canAuth, options := client.Extension("AUTH") - - if canAuth && len(settings.User) > 0 { + if canAuth && len(opts.User) > 0 { var auth smtp.Auth if strings.Contains(options, "CRAM-MD5") { - auth = smtp.CRAMMD5Auth(settings.User, settings.Passwd) + auth = smtp.CRAMMD5Auth(opts.User, opts.Passwd) } else if strings.Contains(options, "PLAIN") { - auth = smtp.PlainAuth("", settings.User, settings.Passwd, host) + auth = smtp.PlainAuth("", opts.User, opts.Passwd, host) } else if strings.Contains(options, "LOGIN") { // Patch for AUTH LOGIN - auth = LoginAuth(settings.User, settings.Passwd) + auth = LoginAuth(opts.User, opts.Passwd) } if auth != nil { @@ -179,15 +156,11 @@ func sendMail(settings *setting.Mailer, recipients []string, msgContent []byte) } } - if fromAddress, err := mail.ParseAddress(settings.From); err != nil { + if err = client.Mail(from); err != nil { return err - } else { - if err = client.Mail(fromAddress.Address); err != nil { - return err - } } - for _, rec := range recipients { + for _, rec := range to { if err = client.Rcpt(rec); err != nil { return err } @@ -196,71 +169,44 @@ func sendMail(settings *setting.Mailer, recipients []string, msgContent []byte) w, err := client.Data() if err != nil { return err - } - if _, err = w.Write([]byte(msgContent)); err != nil { + } else if _, err = msg.WriteTo(w); err != nil { return err - } - - if err = w.Close(); err != nil { + } else if err = w.Close(); err != nil { return err } return client.Quit() } -// Direct Send mail message -func Send(msg *Message) (int, error) { - log.Trace("Sending mails to: %s", strings.Join(msg.To, ", ")) - - // get message body - content := msg.Content() - - if len(msg.To) == 0 { - return 0, fmt.Errorf("empty receive emails") - } else if len(msg.Body) == 0 { - return 0, fmt.Errorf("empty email body") - } +func processMailQueue() { + sender := &Sender{} - if msg.Massive { - // send mail to multiple emails one by one - num := 0 - for _, to := range msg.To { - body := []byte("To: " + to + "\r\n" + content) - err := sendMail(setting.MailService, []string{to}, body) - if err != nil { - return num, err + 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(4, "Fail to send e-mails %s: %s - %v", msg.GetHeader("To"), msg.Info, err) + } else { + log.Trace("E-mails sent %s: %s", msg.GetHeader("To"), msg.Info) } - num++ } - return num, nil - } else { - body := []byte("To: " + strings.Join(msg.To, ",") + "\r\n" + content) + } +} - // send to multiple emails in one message - err := sendMail(setting.MailService, msg.To, body) - if err != nil { - return 0, err - } else { - return 1, nil - } +var mailQueue chan *Message + +func NewContext() { + if setting.MailService == nil { + return } + + mailQueue = make(chan *Message, setting.MailService.QueueLength) + go processMailQueue() } -// Async Send mail message func SendAsync(msg *Message) { go func() { mailQueue <- msg }() } - -// Create html mail message -func NewHtmlMessage(To []string, From, Subject, Body string) Message { - return Message{ - To: To, - From: setting.MailService.From, - ReplyTo: From, - Subject: Subject, - Body: Body, - Type: "html", - } -} |