gomail/message.go

316 lines
7.4 KiB
Go
Raw Normal View History

2014-10-15 23:47:07 +08:00
// Package gomail provides a simple interface to send emails.
//
// More info on Github: https://github.com/go-gomail/gomail
package gomail
import (
"bytes"
"io"
"os"
2014-10-15 23:47:07 +08:00
"path/filepath"
"time"
)
// Message represents an email.
type Message struct {
header header
parts []part
attachments []*File
embedded []*File
charset string
encoding Encoding
hEncoder mimeEncoder
buf bytes.Buffer
2014-10-15 23:47:07 +08:00
}
type header map[string][]string
type part struct {
contentType string
copier func(io.Writer) error
2014-10-15 23:47:07 +08:00
}
// NewMessage creates a new message. It uses UTF-8 and quoted-printable encoding
// by default.
func NewMessage(settings ...MessageSetting) *Message {
2015-07-15 05:34:21 +08:00
m := &Message{
2014-10-15 23:47:07 +08:00
header: make(header),
charset: "UTF-8",
encoding: QuotedPrintable,
}
2015-07-15 05:34:21 +08:00
m.applySettings(settings)
2014-10-15 23:47:07 +08:00
2015-07-15 05:34:21 +08:00
if m.encoding == Base64 {
m.hEncoder = bEncoding
2014-10-15 23:47:07 +08:00
} else {
m.hEncoder = qEncoding
2014-10-15 23:47:07 +08:00
}
2015-07-15 05:34:21 +08:00
return m
2014-10-15 23:47:07 +08:00
}
// Reset resets the message so it can be reused. The message keeps its previous
// settings so it is in the same state that after a call to NewMessage.
2015-07-15 05:34:21 +08:00
func (m *Message) Reset() {
for k := range m.header {
delete(m.header, k)
}
2015-07-15 05:34:21 +08:00
m.parts = nil
m.attachments = nil
m.embedded = nil
}
2015-07-15 05:34:21 +08:00
func (m *Message) applySettings(settings []MessageSetting) {
2014-10-15 23:47:07 +08:00
for _, s := range settings {
2015-07-15 05:34:21 +08:00
s(m)
2014-10-15 23:47:07 +08:00
}
}
// A MessageSetting can be used as an argument in NewMessage to configure an
// email.
2015-07-15 05:34:21 +08:00
type MessageSetting func(m *Message)
2014-10-15 23:47:07 +08:00
// SetCharset is a message setting to set the charset of the email.
//
// Example:
//
2015-07-17 04:35:43 +08:00
// m := gomail.NewMessage(gomail.SetCharset("ISO-8859-1"))
2014-10-15 23:47:07 +08:00
func SetCharset(charset string) MessageSetting {
2015-07-15 05:34:21 +08:00
return func(m *Message) {
m.charset = charset
2014-10-15 23:47:07 +08:00
}
}
// SetEncoding is a message setting to set the encoding of the email.
//
// Example:
//
2015-07-17 04:35:43 +08:00
// m := gomail.NewMessage(gomail.SetEncoding(gomail.Base64))
2014-10-15 23:47:07 +08:00
func SetEncoding(enc Encoding) MessageSetting {
2015-07-15 05:34:21 +08:00
return func(m *Message) {
m.encoding = enc
2014-10-15 23:47:07 +08:00
}
}
// Encoding represents a MIME encoding scheme like quoted-printable or base64.
type Encoding string
const (
// QuotedPrintable represents the quoted-printable encoding as defined in
// RFC 2045.
QuotedPrintable Encoding = "quoted-printable"
// Base64 represents the base64 encoding as defined in RFC 2045.
Base64 Encoding = "base64"
2014-10-28 15:35:50 +08:00
// Unencoded can be used to avoid encoding the body of an email. The headers
// will still be encoded using quoted-printable encoding.
Unencoded Encoding = "8bit"
2014-10-15 23:47:07 +08:00
)
// SetHeader sets a value to the given header field.
2015-07-15 05:34:21 +08:00
func (m *Message) SetHeader(field string, value ...string) {
2014-10-15 23:47:07 +08:00
for i := range value {
2015-07-15 05:34:21 +08:00
value[i] = m.encodeHeader(value[i])
2014-10-15 23:47:07 +08:00
}
2015-07-15 05:34:21 +08:00
m.header[field] = value
2014-10-15 23:47:07 +08:00
}
// SetHeaders sets the message headers.
//
// Example:
//
2015-07-15 05:34:21 +08:00
// m.SetHeaders(map[string][]string{
2014-10-15 23:47:07 +08:00
// "From": {"alex@example.com"},
// "To": {"bob@example.com", "cora@example.com"},
// "Subject": {"Hello"},
// })
2015-07-15 05:34:21 +08:00
func (m *Message) SetHeaders(h map[string][]string) {
2014-10-15 23:47:07 +08:00
for k, v := range h {
2015-07-15 05:34:21 +08:00
m.SetHeader(k, v...)
2014-10-15 23:47:07 +08:00
}
}
// SetAddressHeader sets an address to the given header field.
2015-07-15 05:34:21 +08:00
func (m *Message) SetAddressHeader(field, address, name string) {
m.header[field] = []string{m.FormatAddress(address, name)}
2014-10-15 23:47:07 +08:00
}
// FormatAddress formats an address and a name as a valid RFC 5322 address.
2015-07-15 05:34:21 +08:00
func (m *Message) FormatAddress(address, name string) string {
enc := m.encodeHeader(name)
if enc == name {
2015-07-15 05:34:21 +08:00
m.buf.WriteByte('"')
for i := 0; i < len(name); i++ {
b := name[i]
if b == '\\' || b == '"' {
2015-07-15 05:34:21 +08:00
m.buf.WriteByte('\\')
}
2015-07-15 05:34:21 +08:00
m.buf.WriteByte(b)
}
2015-07-15 05:34:21 +08:00
m.buf.WriteByte('"')
} else if hasSpecials(name) {
m.buf.WriteString(bEncoding.Encode(m.charset, name))
} else {
2015-07-15 05:34:21 +08:00
m.buf.WriteString(enc)
}
2015-07-15 05:34:21 +08:00
m.buf.WriteString(" <")
m.buf.WriteString(address)
m.buf.WriteByte('>')
2015-07-15 05:34:21 +08:00
addr := m.buf.String()
m.buf.Reset()
return addr
}
func hasSpecials(text string) bool {
for i := 0; i < len(text); i++ {
switch c := text[i]; c {
case '(', ')', '<', '>', '[', ']', ':', ';', '@', '\\', ',', '.', '"':
return true
}
}
return false
}
2015-07-15 05:34:21 +08:00
func (m *Message) encodeHeader(value string) string {
return m.hEncoder.Encode(m.charset, value)
2014-10-15 23:47:07 +08:00
}
// SetDateHeader sets a date to the given header field.
2015-07-15 05:34:21 +08:00
func (m *Message) SetDateHeader(field string, date time.Time) {
m.header[field] = []string{m.FormatDate(date)}
2014-10-15 23:47:07 +08:00
}
// FormatDate formats a date as a valid RFC 5322 date.
2015-07-15 05:34:21 +08:00
func (m *Message) FormatDate(date time.Time) string {
2015-02-28 23:46:44 +08:00
return date.Format(time.RFC1123Z)
2014-10-15 23:47:07 +08:00
}
// GetHeader gets a header field.
2015-07-15 05:34:21 +08:00
func (m *Message) GetHeader(field string) []string {
return m.header[field]
2014-10-15 23:47:07 +08:00
}
// DelHeader deletes a header field.
2015-07-15 05:34:21 +08:00
func (m *Message) DelHeader(field string) {
delete(m.header, field)
2014-10-15 23:47:07 +08:00
}
// SetBody sets the body of the message.
2015-07-15 05:34:21 +08:00
func (m *Message) SetBody(contentType, body string) {
m.parts = []part{
2015-07-23 04:38:02 +08:00
{
2014-10-15 23:47:07 +08:00
contentType: contentType,
copier: func(w io.Writer) error {
_, err := io.WriteString(w, body)
return err
},
2014-10-15 23:47:07 +08:00
},
}
}
// AddAlternative adds an alternative part to the message. Commonly used to
2014-10-15 23:47:07 +08:00
// send HTML emails that default to the plain text version for backward
// compatibility.
//
// Example:
//
2015-07-15 05:34:21 +08:00
// m.SetBody("text/plain", "Hello!")
// m.AddAlternative("text/html", "<p>Hello!</p>")
2014-10-15 23:47:07 +08:00
//
// More info: http://en.wikipedia.org/wiki/MIME#Alternative
2015-07-15 05:34:21 +08:00
func (m *Message) AddAlternative(contentType, body string) {
m.parts = append(m.parts,
2014-10-15 23:47:07 +08:00
part{
contentType: contentType,
copier: func(w io.Writer) error {
_, err := io.WriteString(w, body)
return err
},
2014-10-15 23:47:07 +08:00
},
)
}
// AddAlternativeWriter adds an alternative part to the message. It can be
// useful with the text/template and html/template packages.
2014-10-15 23:47:07 +08:00
//
// Example:
//
// t := template.Must(template.New("example").Parse("Hello {{.}}!"))
2015-07-15 05:34:21 +08:00
// m.AddAlternativeWriter("text/plain", func(w io.Writer) error {
// return t.Execute(w, "Bob")
// })
2015-07-15 05:34:21 +08:00
func (m *Message) AddAlternativeWriter(contentType string, f func(io.Writer) error) {
m.parts = []part{
2015-07-23 04:38:02 +08:00
{
2014-10-15 23:47:07 +08:00
contentType: contentType,
copier: f,
2014-10-15 23:47:07 +08:00
},
}
2014-10-15 23:47:07 +08:00
}
// A File represents a file that can be attached or embedded in an email.
type File struct {
// Name represents the base name of the file. If the file is attached to the
// message it is the name of the attachment.
Name string
// Header represents the MIME header of the message part that contains the
2015-07-17 04:35:43 +08:00
// file content. It is empty by default. Mandatory headers are automatically
// added if they are not sent when sending the email.
Header map[string][]string
// Copier is a function run when the message is sent. It should copy the
// content of the file to w.
Copier func(w io.Writer) error
2014-10-15 23:47:07 +08:00
}
// NewFile creates a File from the given filename.
func NewFile(filename string) *File {
return &File{
Name: filepath.Base(filename),
Header: make(map[string][]string),
Copier: func(w io.Writer) error {
h, err := os.Open(filename)
if err != nil {
return err
}
if _, err := io.Copy(w, h); err != nil {
h.Close()
return err
}
return h.Close()
},
2014-10-15 23:47:07 +08:00
}
}
func (f *File) setHeader(field string, value ...string) {
f.Header[field] = value
2014-10-15 23:47:07 +08:00
}
// Attach attaches the files to the email.
2015-07-17 04:35:43 +08:00
//
// Example:
//
// m.Attach(gomail.NewFile("/tmp/image.jpg"))
2015-07-15 05:34:21 +08:00
func (m *Message) Attach(f ...*File) {
if m.attachments == nil {
m.attachments = f
2014-10-15 23:47:07 +08:00
} else {
2015-07-15 05:34:21 +08:00
m.attachments = append(m.attachments, f...)
2014-10-15 23:47:07 +08:00
}
}
// Embed embeds the images to the email.
//
// Example:
//
2015-07-17 01:35:21 +08:00
// m.Embed(gomail.NewFile("/tmp/image.jpg"))
2015-07-15 05:34:21 +08:00
// m.SetBody("text/html", `<img src="cid:image.jpg" alt="My image" />`)
func (m *Message) Embed(image ...*File) {
if m.embedded == nil {
m.embedded = image
2014-10-15 23:47:07 +08:00
} else {
2015-07-15 05:34:21 +08:00
m.embedded = append(m.embedded, image...)
2014-10-15 23:47:07 +08:00
}
}