1
0
Fork 0
mirror of https://github.com/documize/community.git synced 2025-08-02 20:15:26 +02:00

New SMTP library and refactoring of mailer code

This commit is contained in:
sauls8t 2018-03-07 18:52:19 +00:00
parent 99220641f3
commit bd43319bb2
39 changed files with 3163 additions and 1268 deletions

View file

@ -76,7 +76,7 @@ background-color: #f6f6f6;
</tr>
<tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; margin: 0; padding: 0;">
<td class="content-block" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;" valign="top">
<a href="{{.Url}}" class="btn-primary" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; color: #FFF; text-decoration: none; line-height: 2; font-weight: bold; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; background: #4ccb6a; margin: 0; padding: 0; border-color: #4ccb6a; border-style: solid; border-width: 10px 20px;">View document</a>
<a href="{{.URL}}" class="btn-primary" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; color: #FFF; text-decoration: none; line-height: 2; font-weight: bold; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; background: #4ccb6a; margin: 0; padding: 0; border-color: #4ccb6a; border-style: solid; border-width: 10px 20px;">View document</a>
</td>
</tr>
<tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; margin: 0; padding: 0;">

View file

@ -14,57 +14,50 @@
package mail
import (
"bytes"
"fmt"
"html/template"
"github.com/documize/community/server/web"
"github.com/documize/community/domain/smtp"
)
// DocumentApprover notifies user who has just been granted document approval rights.
func (m *Mailer) DocumentApprover(recipient, inviter, url, document string) {
method := "DocumentApprover"
m.LoadCredentials()
file, err := web.ReadFile("mail/document-approver.html")
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to load email template", method), err)
return
}
emailTemplate := string(file)
m.Initialize()
// check inviter name
if inviter == "Hello You" || len(inviter) == 0 {
inviter = "Your colleague"
}
subject := fmt.Sprintf("%s has granted you document approval", inviter)
e := NewEmail()
e.From = m.Credentials.SMTPsender
e.To = []string{recipient}
e.Subject = subject
em := smtp.EmailMessage{}
em.Subject = fmt.Sprintf("%s has granted you document approval", inviter)
em.ToEmail = recipient
em.ToName = recipient
parameters := struct {
Subject string
Inviter string
Url string
URL string
Document string
}{
subject,
em.Subject,
inviter,
url,
document,
}
buffer := new(bytes.Buffer)
t := template.Must(template.New("emailTemplate").Parse(emailTemplate))
t.Execute(buffer, &parameters)
e.HTML = buffer.Bytes()
html, err := m.ParseTemplate("mail/document-approver.html", parameters)
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to load email template", method), err)
return
}
em.BodyHTML = html
err = e.Send(m.GetHost(), m.GetAuth())
ok, err := smtp.SendMessage(m.Dialer, m.Config, em)
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to send email", method), err)
}
if !ok {
m.Runtime.Log.Info(fmt.Sprintf("%s unable to send email"))
}
}

View file

@ -72,7 +72,7 @@ background-color: #f6f6f6;
</tr>
<tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; margin: 0; padding: 0;">
<td class="content-block" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;" valign="top">
<a href="{{.Url}}" class="btn-primary" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; color: #FFF; text-decoration: none; line-height: 2; font-weight: bold; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; background: #4ccb6a; margin: 0; padding: 0; border-color: #4ccb6a; border-style: solid; border-width: 10px 20px;">Click here to access Documize</a>
<a href="{{.URL}}" class="btn-primary" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; color: #FFF; text-decoration: none; line-height: 2; font-weight: bold; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; background: #4ccb6a; margin: 0; padding: 0; border-color: #4ccb6a; border-style: solid; border-width: 10px 20px;">Click here to access Documize</a>
</td>
</tr>
<tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; margin: 0; padding: 0;">

View file

@ -82,7 +82,7 @@ background-color: #f6f6f6;
</tr>
<tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; margin: 0; padding: 0;">
<td class="content-block" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;" valign="top">
<a href="{{.Url}}" class="btn-primary" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; color: #FFF; text-decoration: none; line-height: 2; font-weight: bold; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; background: #4ccb6a; margin: 0; padding: 0; border-color: #4ccb6a; border-style: solid; border-width: 10px 20px;">Click here to access Documize</a>
<a href="{{.URL}}" class="btn-primary" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; color: #FFF; text-decoration: none; line-height: 2; font-weight: bold; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; background: #4ccb6a; margin: 0; padding: 0; border-color: #4ccb6a; border-style: solid; border-width: 10px 20px;">Click here to access Documize</a>
</td>
</tr>
<tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; margin: 0; padding: 0;">

View file

@ -9,61 +9,57 @@
//
// https://documize.com
// jshint ignore:start
package mail
import (
"net/smtp"
"strings"
"bytes"
"html/template"
"github.com/documize/community/core/env"
"github.com/documize/community/core/mail"
"github.com/documize/community/domain"
"github.com/documize/community/domain/setting"
ds "github.com/documize/community/domain/smtp"
"github.com/documize/community/server/web"
)
// Mailer provides emailing facilities
type Mailer struct {
Runtime *env.Runtime
Store *domain.Store
Context domain.RequestContext
Credentials Credentials
Runtime *env.Runtime
Store *domain.Store
Context domain.RequestContext
Config ds.Config
Dialer *mail.Dialer
}
// Credentials holds SMTP endpoint and authentication methods
type Credentials struct {
SMTPuserid string
SMTPpassword string
SMTPhost string
SMTPport string
SMTPsender string
// Initialize prepares mailer instance for action.
func (m *Mailer) Initialize() {
m.Config = setting.GetSMTPConfig(m.Store)
m.Dialer, _ = ds.Connect(m.Config)
}
// GetAuth to return SMTP authentication details
func (m *Mailer) GetAuth() smtp.Auth {
a := smtp.PlainAuth("", m.Credentials.SMTPuserid, m.Credentials.SMTPpassword, m.Credentials.SMTPhost)
return a
// Send prepares and sends email.
func (m *Mailer) Send(em ds.EmailMessage) (ok bool, err error) {
ok, err = ds.SendMessage(m.Dialer, m.Config, em)
return
}
// GetHost to return SMTP host details
func (m *Mailer) GetHost() string {
h := m.Credentials.SMTPhost + ":" + m.Credentials.SMTPport
return h
}
// LoadCredentials loads up SMTP details from database
func (m *Mailer) LoadCredentials() {
userID, _ := m.Store.Setting.Get("SMTP", "userid")
m.Credentials.SMTPuserid = strings.TrimSpace(userID)
pwd, _ := m.Store.Setting.Get("SMTP", "password")
m.Credentials.SMTPpassword = strings.TrimSpace(pwd)
host, _ := m.Store.Setting.Get("SMTP", "host")
m.Credentials.SMTPhost = strings.TrimSpace(host)
port, _ := m.Store.Setting.Get("SMTP", "port")
m.Credentials.SMTPport = strings.TrimSpace(port)
sender, _ := m.Store.Setting.Get("SMTP", "sender")
m.Credentials.SMTPsender = strings.TrimSpace(sender)
// ParseTemplate produces email template.
func (m *Mailer) ParseTemplate(filename string, params interface{}) (html string, err error) {
html = ""
file, err := web.ReadFile(filename)
if err != nil {
return
}
emailTemplate := string(file)
buffer := new(bytes.Buffer)
t := template.Must(template.New("emailTemplate").Parse(emailTemplate))
t.Execute(buffer, &params)
html = buffer.String()
return
}

View file

@ -79,7 +79,7 @@ background-color: #f6f6f6;
</tr>
<tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; margin: 0; padding: 0;">
<td class="content-block" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;" valign="top">
<a href="{{.Url}}" class="btn-primary" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; color: #FFF; text-decoration: none; line-height: 2; font-weight: bold; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; background: #4ccb6a; margin: 0; padding: 0; border-color: #4ccb6a; border-style: solid; border-width: 10px 20px;">Click here to reset your password</a>
<a href="{{.URL}}" class="btn-primary" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; color: #FFF; text-decoration: none; line-height: 2; font-weight: bold; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; background: #4ccb6a; margin: 0; padding: 0; border-color: #4ccb6a; border-style: solid; border-width: 10px 20px;">Click here to reset your password</a>
</td>
</tr>
<tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; margin: 0; padding: 0;">

View file

@ -75,7 +75,7 @@ background-color: #f6f6f6;
</tr>
<tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; margin: 0; padding: 0;">
<td class="content-block" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;" valign="top">
<a href="{{.Url}}" class="btn-primary" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; color: #FFF; text-decoration: none; line-height: 2; font-weight: bold; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; background: #4ccb6a; margin: 0; padding: 0; border-color: #4ccb6a; border-style: solid; border-width: 10px 20px;">Login to Documize</a>
<a href="{{.URL}}" class="btn-primary" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; color: #FFF; text-decoration: none; line-height: 2; font-weight: bold; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; background: #4ccb6a; margin: 0; padding: 0; border-color: #4ccb6a; border-style: solid; border-width: 10px 20px;">Login to Documize</a>
</td>
</tr>
<tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; margin: 0; padding: 0;">

View file

@ -81,7 +81,7 @@ background-color: #f6f6f6;
</tr>
<tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; margin: 0; padding: 0;">
<td class="content-block" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;" valign="top">
<a href="{{.Url}}" class="btn-primary" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; color: #FFF; text-decoration: none; line-height: 2; font-weight: bold; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; background: #4ccb6a; margin: 0; padding: 0; border-color: #4ccb6a; border-style: solid; border-width: 10px 20px;">Go to Documize</a>
<a href="{{.URL}}" class="btn-primary" style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; color: #FFF; text-decoration: none; line-height: 2; font-weight: bold; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; background: #4ccb6a; margin: 0; padding: 0; border-color: #4ccb6a; border-style: solid; border-width: 10px 20px;">Go to Documize</a>
</td>
</tr>
<tr style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; margin: 0; padding: 0;">

View file

@ -1,374 +0,0 @@
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com
/*
Elements of the software in this file were modified from github.com/jordan-wright/email and
are subject to the licence below:
The MIT License (MIT)
Copyright (c) 2013 Jordan Wright
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// Package mail sends transactional emails.
// The code in smtp.go is designed to provide an "email interface for humans".
// Designed to be robust and flexible, the email package aims to make sending email easy without getting in the way.
package mail
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"net/mail"
"net/smtp"
"net/textproto"
"os"
"path/filepath"
"strings"
"time"
)
const (
// MaxLineLength is the maximum line length per RFC 2045
MaxLineLength = 76
)
// Email is the type used for email messages
type Email struct {
From string
To []string
Bcc []string
Cc []string
Subject string
Text []byte // Plaintext message (optional)
HTML []byte // Html message (optional)
Headers textproto.MIMEHeader
Attachments []*Attachment
ReadReceipt []string
}
// NewEmail creates an Email, and returns the pointer to it.
func NewEmail() *Email {
return &Email{Headers: textproto.MIMEHeader{}}
}
// Attach is used to attach content from an io.Reader to the email.
// Required parameters include an io.Reader, the desired filename for the attachment, and the Content-Type
// The function will return the created Attachment for reference, as well as nil for the error, if successful.
func (e *Email) Attach(r io.Reader, filename string, c string) (a *Attachment, err error) {
var buffer bytes.Buffer
if _, err = io.Copy(&buffer, r); err != nil {
return
}
at := &Attachment{
Filename: filename,
Header: textproto.MIMEHeader{},
Content: buffer.Bytes(),
}
// Get the Content-Type to be used in the MIMEHeader
if c != "" {
at.Header.Set("Content-Type", c)
} else {
// If the Content-Type is blank, set the Content-Type to "application/octet-stream"
at.Header.Set("Content-Type", "application/octet-stream")
}
at.Header.Set("Content-Disposition", fmt.Sprintf("attachment;\r\n filename=\"%s\"", filename))
at.Header.Set("Content-ID", fmt.Sprintf("<%s>", filename))
at.Header.Set("Content-Transfer-Encoding", "base64")
e.Attachments = append(e.Attachments, at)
return at, nil
}
// AttachFile is used to attach content to the email.
// It attempts to open the file referenced by filename and, if successful, creates an Attachment.
// This Attachment is then appended to the slice of Email.Attachments.
// The function will then return the Attachment for reference, as well as nil for the error, if successful.
func (e *Email) AttachFile(filename string) (a *Attachment, err error) {
f, err := os.Open(filename)
if err != nil {
return
}
ct := mime.TypeByExtension(filepath.Ext(filename))
basename := filepath.Base(filename)
return e.Attach(f, basename, ct)
}
// msgHeaders merges the Email's various fields and custom headers together in a
// standards compliant way to create a MIMEHeader to be used in the resulting
// message. It does not alter e.Headers.
//
// "e"'s fields To, Cc, From, Subject will be used unless they are present in
// e.Headers. Unless set in e.Headers, "Date" will filled with the current time.
func (e *Email) msgHeaders() textproto.MIMEHeader {
res := make(textproto.MIMEHeader, len(e.Headers)+4)
if e.Headers != nil {
for _, h := range []string{"To", "Cc", "From", "Subject", "Date"} {
if v, ok := e.Headers[h]; ok {
res[h] = v
}
}
}
// Set headers if there are values.
if _, ok := res["To"]; !ok && len(e.To) > 0 {
res.Set("To", strings.Join(e.To, ", "))
}
if _, ok := res["Cc"]; !ok && len(e.Cc) > 0 {
res.Set("Cc", strings.Join(e.Cc, ", "))
}
if _, ok := res["Subject"]; !ok && e.Subject != "" {
res.Set("Subject", e.Subject)
}
// Date and From are required headers.
if _, ok := res["From"]; !ok {
res.Set("From", e.From)
}
if _, ok := res["Date"]; !ok {
res.Set("Date", time.Now().Format(time.RFC1123Z))
}
if _, ok := res["Mime-Version"]; !ok {
res.Set("Mime-Version", "1.0")
}
for field, vals := range e.Headers {
if _, ok := res[field]; !ok {
res[field] = vals
}
}
return res
}
// Bytes converts the Email object to a []byte representation, including all needed MIMEHeaders, boundaries, etc.
func (e *Email) Bytes() ([]byte, error) {
// TODO: better guess buffer size
buff := bytes.NewBuffer(make([]byte, 0, 4096))
headers := e.msgHeaders()
w := multipart.NewWriter(buff)
// TODO: determine the content type based on message/attachment mix.
headers.Set("Content-Type", "multipart/mixed;\r\n boundary="+w.Boundary())
headerToBytes(buff, headers)
io.WriteString(buff, "\r\n")
// Start the multipart/mixed part
fmt.Fprintf(buff, "--%s\r\n", w.Boundary())
header := textproto.MIMEHeader{}
// Check to see if there is a Text or HTML field
if len(e.Text) > 0 || len(e.HTML) > 0 {
subWriter := multipart.NewWriter(buff)
// Create the multipart alternative part
header.Set("Content-Type", fmt.Sprintf("multipart/alternative;\r\n boundary=%s\r\n", subWriter.Boundary()))
// Write the header
headerToBytes(buff, header)
// Create the body sections
if len(e.Text) > 0 {
header.Set("Content-Type", fmt.Sprintf("text/plain; charset=UTF-8"))
header.Set("Content-Transfer-Encoding", "quoted-printable")
if _, err := subWriter.CreatePart(header); err != nil {
return nil, err
}
// Write the text
if err := quotePrintEncode(buff, e.Text); err != nil {
return nil, err
}
}
if len(e.HTML) > 0 {
header.Set("Content-Type", fmt.Sprintf("text/html; charset=UTF-8"))
header.Set("Content-Transfer-Encoding", "quoted-printable")
if _, err := subWriter.CreatePart(header); err != nil {
return nil, err
}
// Write the text
if err := quotePrintEncode(buff, e.HTML); err != nil {
return nil, err
}
}
if err := subWriter.Close(); err != nil {
return nil, err
}
}
// Create attachment part, if necessary
for _, a := range e.Attachments {
ap, err := w.CreatePart(a.Header)
if err != nil {
return nil, err
}
// Write the base64Wrapped content to the part
base64Wrap(ap, a.Content)
}
if err := w.Close(); err != nil {
return nil, err
}
return buff.Bytes(), nil
}
// Send an email using the given host and SMTP auth (optional), returns any error thrown by smtp.SendMail
// This function merges the To, Cc, and Bcc fields and calls the smtp.SendMail function using the Email.Bytes() output as the message
func (e *Email) Send(addr string, a smtp.Auth) error {
// Merge the To, Cc, and Bcc fields
to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
for i := 0; i < len(to); i++ {
addr, err := mail.ParseAddress(to[i])
if err != nil {
return err
}
to[i] = addr.Address
}
// Check to make sure there is at least one recipient and one "From" address
if e.From == "" || len(to) == 0 {
return errors.New("Must specify at least one From address and one To address")
}
from, err := mail.ParseAddress(e.From)
if err != nil {
return err
}
raw, err := e.Bytes()
if err != nil {
return err
}
return smtpSendMail(addr, a, from.Address, to, raw)
}
var smtpSendMail = smtp.SendMail // so that it can be overloaded for testing
// Attachment is a struct representing an email attachment.
// Based on the mime/multipart.FileHeader struct, Attachment contains the name, MIMEHeader, and content of the attachment in question
type Attachment struct {
Filename string
Header textproto.MIMEHeader
Content []byte
}
// quotePrintEncode writes the quoted-printable text to the IO Writer (according to RFC 2045)
func quotePrintEncode(w io.Writer, body []byte) error {
var buf [3]byte
mc := 0
for _, c := range body {
// We're assuming Unix style text formats as input (LF line break), and
// quoted-printable uses CRLF line breaks. (Literal CRs will become
// "=0D", but probably shouldn't be there to begin with!)
if c == '\n' {
_, err := io.WriteString(w, "\r\n")
if err != nil {
return err
}
mc = 0
continue
}
var nextOut []byte
if isPrintable[c] {
buf[0] = c
nextOut = buf[:1]
} else {
nextOut = buf[:]
qpEscape(nextOut, c)
}
// Add a soft line break if the next (encoded) byte would push this line
// to or past the limit.
if mc+len(nextOut) >= MaxLineLength {
if _, err := io.WriteString(w, "=\r\n"); err != nil {
return err
}
mc = 0
}
if _, err := w.Write(nextOut); err != nil {
return err
}
mc += len(nextOut)
}
// No trailing end-of-line?? Soft line break, then. TODO: is this sane?
if mc > 0 {
_, err := io.WriteString(w, "=\r\n")
if err != nil {
return err
}
}
return nil
}
// isPrintable holds true if the byte given is "printable" according to RFC 2045, false otherwise
var isPrintable [256]bool
func init() {
for c := '!'; c <= '<'; c++ {
isPrintable[c] = true
}
for c := '>'; c <= '~'; c++ {
isPrintable[c] = true
}
isPrintable[' '] = true
isPrintable['\n'] = true
isPrintable['\t'] = true
}
// qpEscape is a helper function for quotePrintEncode which escapes a
// non-printable byte. Expects len(dest) == 3.
func qpEscape(dest []byte, c byte) {
const nums = "0123456789ABCDEF"
dest[0] = '='
dest[1] = nums[(c&0xf0)>>4]
dest[2] = nums[(c & 0xf)]
}
// base64Wrap encodes the attachment content, and wraps it according to RFC 2045 standards (every 76 chars)
// The output is then written to the specified io.Writer
func base64Wrap(w io.Writer, b []byte) {
// 57 raw bytes per 76-byte base64 line.
const maxRaw = 57
// Buffer for each line, including trailing CRLF.
buffer := make([]byte, MaxLineLength+len("\r\n"))
copy(buffer[MaxLineLength:], "\r\n")
// Process raw chunks until there's no longer enough to fill a line.
for len(b) >= maxRaw {
base64.StdEncoding.Encode(buffer, b[:maxRaw])
w.Write(buffer)
b = b[maxRaw:]
}
// Handle the last chunk of bytes.
if len(b) > 0 {
out := buffer[:base64.StdEncoding.EncodedLen(len(b))]
base64.StdEncoding.Encode(out, b)
out = append(out, "\r\n"...)
w.Write(out)
}
}
// headerToBytes renders "header" to "buff". If there are multiple values for a
// field, multiple "Field: value\r\n" lines will be emitted.
func headerToBytes(buff *bytes.Buffer, header textproto.MIMEHeader) {
for field, vals := range header {
for _, subval := range vals {
io.WriteString(buff, field+": "+subval+"\r\n")
}
}
}

View file

@ -9,114 +9,100 @@
//
// https://documize.com
// jshint ignore:start
package mail
import (
"bytes"
"fmt"
"html/template"
"github.com/documize/community/server/web"
"github.com/documize/community/domain/smtp"
)
// ShareSpaceExistingUser provides an existing user with a link to a newly shared space.
func (m *Mailer) ShareSpaceExistingUser(recipient, inviter, url, folder, intro string) {
method := "ShareSpaceExistingUser"
m.LoadCredentials()
file, err := web.ReadFile("mail/share-space-existing-user.html")
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to load email template", method), err)
return
}
emailTemplate := string(file)
m.Initialize()
// check inviter name
if inviter == "Hello You" || len(inviter) == 0 {
inviter = "Your colleague"
}
subject := fmt.Sprintf("%s has shared %s with you", inviter, folder)
e := NewEmail()
e.From = m.Credentials.SMTPsender
e.To = []string{recipient}
e.Subject = subject
em := smtp.EmailMessage{}
em.Subject = fmt.Sprintf("%s has shared %s with you", inviter, folder)
em.ToEmail = recipient
em.ToName = recipient
parameters := struct {
Subject string
Inviter string
Url string
URL string
Folder string
Intro string
}{
subject,
em.Subject,
inviter,
url,
folder,
intro,
}
buffer := new(bytes.Buffer)
t := template.Must(template.New("emailTemplate").Parse(emailTemplate))
t.Execute(buffer, &parameters)
e.HTML = buffer.Bytes()
html, err := m.ParseTemplate("mail/share-space-existing-user.html", parameters)
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to load email template", method), err)
return
}
em.BodyHTML = html
err = e.Send(m.GetHost(), m.GetAuth())
ok, err := smtp.SendMessage(m.Dialer, m.Config, em)
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to send email", method), err)
}
if !ok {
m.Runtime.Log.Info(fmt.Sprintf("%s unable to send email"))
}
}
// ShareSpaceNewUser invites new user providing Credentials, explaining the product and stating who is inviting them.
func (m *Mailer) ShareSpaceNewUser(recipient, inviter, url, space, invitationMessage string) {
method := "ShareSpaceNewUser"
m.LoadCredentials()
file, err := web.ReadFile("mail/share-space-new-user.html")
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to load email template", method), err)
return
}
emailTemplate := string(file)
m.Initialize()
// check inviter name
if inviter == "Hello You" || len(inviter) == 0 {
inviter = "Your colleague"
}
subject := fmt.Sprintf("%s has shared %s with you on Documize", inviter, space)
e := NewEmail()
e.From = m.Credentials.SMTPsender
e.To = []string{recipient}
e.Subject = subject
em := smtp.EmailMessage{}
em.Subject = fmt.Sprintf("%s has shared %s with you on Documize", inviter, space)
em.ToEmail = recipient
em.ToName = recipient
parameters := struct {
Subject string
Inviter string
Url string
URL string
Invitation string
Folder string
}{
subject,
em.Subject,
inviter,
url,
invitationMessage,
space,
}
buffer := new(bytes.Buffer)
t := template.Must(template.New("emailTemplate").Parse(emailTemplate))
t.Execute(buffer, &parameters)
e.HTML = buffer.Bytes()
html, err := m.ParseTemplate("mail/share-space-new-user.html", parameters)
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to load email template", method), err)
return
}
em.BodyHTML = html
err = e.Send(m.GetHost(), m.GetAuth())
ok, err := smtp.SendMessage(m.Dialer, m.Config, em)
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to send email", method), err)
}
if !ok {
m.Runtime.Log.Info(fmt.Sprintf("%s unable to send email"))
}
}

View file

@ -9,149 +9,130 @@
//
// https://documize.com
// jshint ignore:start
package mail
import (
"bytes"
"fmt"
"html/template"
"github.com/documize/community/server/web"
"github.com/documize/community/domain/smtp"
)
// InviteNewUser invites someone new providing credentials, explaining the product and stating who is inviting them.
func (m *Mailer) InviteNewUser(recipient, inviter, url, username, password string) {
method := "InviteNewUser"
m.LoadCredentials()
file, err := web.ReadFile("mail/invite-new-user.html")
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to load email template", method), err)
return
}
emailTemplate := string(file)
m.Initialize()
// check inviter name
if inviter == "Hello You" || len(inviter) == 0 {
inviter = "Your colleague"
}
subject := fmt.Sprintf("%s has invited you to Documize", inviter)
e := NewEmail()
e.From = m.Credentials.SMTPsender
e.To = []string{recipient}
e.Subject = subject
em := smtp.EmailMessage{}
em.Subject = fmt.Sprintf("%s has invited you to Documize", inviter)
em.ToEmail = recipient
em.ToName = recipient
parameters := struct {
Subject string
Inviter string
Url string
URL string
Username string
Password string
}{
subject,
em.Subject,
inviter,
url,
recipient,
password,
}
buffer := new(bytes.Buffer)
t := template.Must(template.New("emailTemplate").Parse(emailTemplate))
t.Execute(buffer, &parameters)
e.HTML = buffer.Bytes()
html, err := m.ParseTemplate("mail/invite-new-user.html", parameters)
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to load email template", method), err)
return
}
em.BodyHTML = html
err = e.Send(m.GetHost(), m.GetAuth())
ok, err := smtp.SendMessage(m.Dialer, m.Config, em)
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to send email", method), err)
}
if !ok {
m.Runtime.Log.Info(fmt.Sprintf("%s unable to send email"))
}
}
// InviteExistingUser invites a known user to an organization.
func (m *Mailer) InviteExistingUser(recipient, inviter, url string) {
method := "InviteExistingUser"
m.LoadCredentials()
file, err := web.ReadFile("mail/invite-existing-user.html")
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to load email template", method), err)
return
}
emailTemplate := string(file)
m.Initialize()
// check inviter name
if inviter == "Hello You" || len(inviter) == 0 {
inviter = "Your colleague"
}
subject := fmt.Sprintf("%s has invited you to their Documize account", inviter)
e := NewEmail()
e.From = m.Credentials.SMTPsender
e.To = []string{recipient}
e.Subject = subject
em := smtp.EmailMessage{}
em.Subject = fmt.Sprintf("%s has invited you to their Documize account", inviter)
em.ToEmail = recipient
em.ToName = recipient
parameters := struct {
Subject string
Inviter string
Url string
URL string
}{
subject,
em.Subject,
inviter,
url,
}
buffer := new(bytes.Buffer)
t := template.Must(template.New("emailTemplate").Parse(emailTemplate))
t.Execute(buffer, &parameters)
e.HTML = buffer.Bytes()
html, err := m.ParseTemplate("mail/invite-existing-user.html", parameters)
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to load email template", method), err)
return
}
em.BodyHTML = html
err = e.Send(m.GetHost(), m.GetAuth())
ok, err := smtp.SendMessage(m.Dialer, m.Config, em)
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to send email", method), err)
}
if !ok {
m.Runtime.Log.Info(fmt.Sprintf("%s unable to send email"))
}
}
// PasswordReset sends a reset email with an embedded token.
func (m *Mailer) PasswordReset(recipient, url string) {
method := "PasswordReset"
m.LoadCredentials()
m.Initialize()
file, err := web.ReadFile("mail/password-reset.html")
em := smtp.EmailMessage{}
em.Subject = "Documize password reset request"
em.ToEmail = recipient
em.ToName = recipient
parameters := struct {
Subject string
URL string
}{
em.Subject,
url,
}
html, err := m.ParseTemplate("mail/password-reset.html", parameters)
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to load email template", method), err)
return
}
em.BodyHTML = html
emailTemplate := string(file)
subject := "Documize password reset request"
e := NewEmail()
e.From = m.Credentials.SMTPsender //e.g. "Documize <hello@documize.com>"
e.To = []string{recipient}
e.Subject = subject
parameters := struct {
Subject string
Url string
}{
subject,
url,
}
buffer := new(bytes.Buffer)
t := template.Must(template.New("emailTemplate").Parse(emailTemplate))
t.Execute(buffer, &parameters)
e.HTML = buffer.Bytes()
err = e.Send(m.GetHost(), m.GetAuth())
ok, err := smtp.SendMessage(m.Dialer, m.Config, em)
if err != nil {
m.Runtime.Log.Error(fmt.Sprintf("%s - unable to send email", method), err)
}
if !ok {
m.Runtime.Log.Info(fmt.Sprintf("%s unable to send email"))
}
}

View file

@ -15,6 +15,7 @@ package setting
import (
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
@ -22,6 +23,7 @@ import (
"github.com/documize/community/core/event"
"github.com/documize/community/core/response"
"github.com/documize/community/domain"
"github.com/documize/community/domain/smtp"
"github.com/documize/community/model/audit"
)
@ -91,7 +93,37 @@ func (h *Handler) SetSMTP(w http.ResponseWriter, r *http.Request) {
h.Store.Audit.Record(ctx, audit.EventTypeSystemSMTP)
response.WriteEmpty(w)
// test connection
var result struct {
Success bool `json:"success"`
Message string `json:"message"`
}
result.Message = "Email sent successfully!"
u, err := h.Store.User.Get(ctx, ctx.UserID)
if err != nil {
result.Success = false
result.Message = err.Error()
h.Runtime.Log.Error(method, err)
response.WriteJSON(w, result)
return
}
cfg := GetSMTPConfig(h.Store)
dialer, err := smtp.Connect(cfg)
em := smtp.EmailMessage{}
em.Subject = "Documize SMTP Test"
em.BodyHTML = "<p>This is a test email from Documize using current SMTP settings.</p>"
em.ToEmail = u.Email
em.ToName = u.Fullname()
result.Success, err = smtp.SendMessage(dialer, cfg, em)
if !result.Success {
result.Message = fmt.Sprintf("Unable to send test email: %s", err.Error())
}
response.WriteJSON(w, result)
}
// License returns product license

60
domain/setting/smtp.go Normal file
View file

@ -0,0 +1,60 @@
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com
// Package setting manages both global and user level settings
package setting
import (
"strconv"
"github.com/documize/community/domain"
"github.com/documize/community/domain/smtp"
)
// GetSMTPConfig returns SMTP configuration.
func GetSMTPConfig(s *domain.Store) (c smtp.Config) {
c = smtp.Config{}
// server
c.Host, _ = s.Setting.Get("SMTP", "host")
port, _ := s.Setting.Get("SMTP", "port")
c.Port, _ = strconv.Atoi(port)
// credentials
c.Username, _ = s.Setting.Get("SMTP", "userid")
c.Password, _ = s.Setting.Get("SMTP", "password")
// sender
c.SenderEmail, _ = s.Setting.Get("SMTP", "sender")
c.SenderName, _ = s.Setting.Get("SMTP", "senderName")
if c.SenderName == "" {
c.SenderName = "Documize"
}
// anon auth?
anon, _ := s.Setting.Get("SMTP", "anonymous")
c.AnonymousAuth, _ = strconv.ParseBool(anon)
// base64 encode creds?
b64, _ := s.Setting.Get("SMTP", "base64creds")
c.Base64EncodeCredentials, _ = strconv.ParseBool(b64)
// SSL?
ssl, _ := s.Setting.Get("SMTP", "usessl")
c.UseSSL, _ = strconv.ParseBool(ssl)
// verify SSL?
verifySSL, _ := s.Setting.Get("SMTP", "verifyssl")
c.SkipSSLVerify, _ = strconv.ParseBool(verifySSL)
c.SkipSSLVerify = true
return
}

114
domain/smtp/send.go Normal file
View file

@ -0,0 +1,114 @@
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com
// Package smtp provides access to SMTP server for sending email.
package smtp
import (
"crypto/tls"
"encoding/base64"
"strings"
"github.com/documize/community/core/mail"
)
// Config is used to create SMTP server connection
type Config struct {
// IP/hostname of SMTP server
Host string
// Port number of SMTP server
Port int
// Username for authentication with SMTP server
Username string
// Password for authentication with SMTP server
Password string
// SenderEmail is FROM address
SenderEmail string
// SenderName is FROM display name
SenderName string
// AnonymousAuth does not send username/password to server
AnonymousAuth bool
// Base64EncodeCredentials encodes User and Password as base64 before sending to SMTP server
Base64EncodeCredentials bool
// UseSSL uses SMTP SSL connection with SMTP server
UseSSL bool
// SkipSSLVerify allows unverified certificates
SkipSSLVerify bool
}
// Connect returns open connection to server for sending email
func Connect(c Config) (d *mail.Dialer, err error) {
// prepare credentials
u := strings.TrimSpace(c.Username)
p := strings.TrimSpace(c.Password)
// anonymous, no credentials
if c.AnonymousAuth {
u = ""
p = ""
}
// base64 encode if required
if c.Base64EncodeCredentials {
u = base64.StdEncoding.EncodeToString([]byte(u))
p = base64.StdEncoding.EncodeToString([]byte(p))
}
// basic server
d = mail.NewDialer(c.Host, c.Port, u, p)
// use SSL
d.SSL = c.UseSSL
// verify SSL cert chain
d.TLSConfig = &tls.Config{InsecureSkipVerify: c.SkipSSLVerify}
// TLS mode
d.StartTLSPolicy = mail.OpportunisticStartTLS
return d, nil
}
// EmailMessage represents email to be sent.
type EmailMessage struct {
ToEmail string
ToName string
Subject string
BodyHTML string
}
// SendMessage sends email using specified SMTP connection
func SendMessage(d *mail.Dialer, c Config, em EmailMessage) (b bool, err error) {
m := mail.NewMessage()
// participants
m.SetHeader("From", m.FormatAddress(c.SenderEmail, c.SenderName))
m.SetHeader("To", m.FormatAddress(em.ToEmail, em.ToName))
// content
m.SetHeader("Subject", em.Subject)
m.SetBody("text/html", em.BodyHTML)
// send email
if err = d.DialAndSend(m); err != nil {
return false, err
}
return true, nil
}