email.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. // Package email is designed to provide an "email interface for humans."
  2. // Designed to be robust and flexible, the email package aims to make sending email easy without getting in the way.
  3. package email
  4. import (
  5. "bufio"
  6. "bytes"
  7. "crypto/rand"
  8. "crypto/tls"
  9. "encoding/base64"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "math"
  14. "math/big"
  15. "mime"
  16. "mime/multipart"
  17. "mime/quotedprintable"
  18. "net/mail"
  19. "net/smtp"
  20. "net/textproto"
  21. "os"
  22. "path/filepath"
  23. "strings"
  24. "time"
  25. "unicode"
  26. )
  27. const (
  28. MaxLineLength = 76 // MaxLineLength is the maximum line length per RFC 2045
  29. defaultContentType = "text/plain; charset=us-ascii" // defaultContentType is the default Content-Type according to RFC 2045, section 5.2
  30. )
  31. // ErrMissingBoundary is returned when there is no boundary given for a multipart entity
  32. var ErrMissingBoundary = errors.New("No boundary found for multipart entity")
  33. // ErrMissingContentType is returned when there is no "Content-Type" header for a MIME entity
  34. var ErrMissingContentType = errors.New("No Content-Type found for MIME entity")
  35. // Email is the type used for email messages
  36. type Email struct {
  37. ReplyTo []string
  38. From string
  39. To []string
  40. Bcc []string
  41. Cc []string
  42. Subject string
  43. Text []byte // Plaintext message (optional)
  44. HTML []byte // Html message (optional)
  45. Sender string // override From as SMTP envelope sender (optional)
  46. Headers textproto.MIMEHeader
  47. Attachments []*Attachment
  48. ReadReceipt []string
  49. }
  50. // part is a copyable representation of a multipart.Part
  51. type part struct {
  52. header textproto.MIMEHeader
  53. body []byte
  54. }
  55. // NewEmail creates an Email, and returns the pointer to it.
  56. func NewEmail() *Email {
  57. return &Email{Headers: textproto.MIMEHeader{}}
  58. }
  59. // trimReader is a custom io.Reader that will trim any leading
  60. // whitespace, as this can cause email imports to fail.
  61. type trimReader struct {
  62. rd io.Reader
  63. trimmed bool
  64. }
  65. // Read trims off any unicode whitespace from the originating reader
  66. func (tr *trimReader) Read(buf []byte) (int, error) {
  67. n, err := tr.rd.Read(buf)
  68. if err != nil {
  69. return n, err
  70. }
  71. if !tr.trimmed {
  72. t := bytes.TrimLeftFunc(buf[:n], unicode.IsSpace)
  73. tr.trimmed = true
  74. n = copy(buf, t)
  75. }
  76. return n, err
  77. }
  78. // NewEmailFromReader reads a stream of bytes from an io.Reader, r,
  79. // and returns an email struct containing the parsed data.
  80. // This function expects the data in RFC 5322 format.
  81. func NewEmailFromReader(r io.Reader) (*Email, error) {
  82. e := NewEmail()
  83. s := &trimReader{rd: r}
  84. tp := textproto.NewReader(bufio.NewReader(s))
  85. // Parse the main headers
  86. hdrs, err := tp.ReadMIMEHeader()
  87. if err != nil {
  88. return e, err
  89. }
  90. // Set the subject, to, cc, bcc, and from
  91. for h, v := range hdrs {
  92. switch {
  93. case h == "Subject":
  94. e.Subject = v[0]
  95. subj, err := (&mime.WordDecoder{}).DecodeHeader(e.Subject)
  96. if err == nil && len(subj) > 0 {
  97. e.Subject = subj
  98. }
  99. delete(hdrs, h)
  100. case h == "To":
  101. for _, toA := range v {
  102. w := strings.Split(toA, ",")
  103. for _, to := range w {
  104. tt, err := (&mime.WordDecoder{}).DecodeHeader(strings.TrimSpace(to))
  105. if err == nil {
  106. e.To = append(e.To, tt)
  107. } else {
  108. e.To = append(e.To, to)
  109. }
  110. }
  111. }
  112. delete(hdrs, h)
  113. case h == "Cc":
  114. for _, ccA := range v {
  115. w := strings.Split(ccA, ",")
  116. for _, cc := range w {
  117. tcc, err := (&mime.WordDecoder{}).DecodeHeader(strings.TrimSpace(cc))
  118. if err == nil {
  119. e.Cc = append(e.Cc, tcc)
  120. } else {
  121. e.Cc = append(e.Cc, cc)
  122. }
  123. }
  124. }
  125. delete(hdrs, h)
  126. case h == "Bcc":
  127. for _, bccA := range v {
  128. w := strings.Split(bccA, ",")
  129. for _, bcc := range w {
  130. tbcc, err := (&mime.WordDecoder{}).DecodeHeader(strings.TrimSpace(bcc))
  131. if err == nil {
  132. e.Bcc = append(e.Bcc, tbcc)
  133. } else {
  134. e.Bcc = append(e.Bcc, bcc)
  135. }
  136. }
  137. }
  138. delete(hdrs, h)
  139. case h == "From":
  140. e.From = v[0]
  141. fr, err := (&mime.WordDecoder{}).DecodeHeader(e.From)
  142. if err == nil && len(fr) > 0 {
  143. e.From = fr
  144. }
  145. delete(hdrs, h)
  146. }
  147. }
  148. e.Headers = hdrs
  149. body := tp.R
  150. // Recursively parse the MIME parts
  151. ps, err := parseMIMEParts(e.Headers, body)
  152. if err != nil {
  153. return e, err
  154. }
  155. for _, p := range ps {
  156. if ct := p.header.Get("Content-Type"); ct == "" {
  157. return e, ErrMissingContentType
  158. }
  159. ct, _, err := mime.ParseMediaType(p.header.Get("Content-Type"))
  160. if err != nil {
  161. return e, err
  162. }
  163. // Check if part is an attachment based on the existence of the Content-Disposition header with a value of "attachment".
  164. if cd := p.header.Get("Content-Disposition"); cd != "" {
  165. cd, params, err := mime.ParseMediaType(p.header.Get("Content-Disposition"))
  166. if err != nil {
  167. return e, err
  168. }
  169. filename, filenameDefined := params["filename"]
  170. if cd == "attachment" || (cd == "inline" && filenameDefined){
  171. _, err = e.Attach(bytes.NewReader(p.body), filename, ct)
  172. if err != nil {
  173. return e, err
  174. }
  175. continue
  176. }
  177. }
  178. switch {
  179. case ct == "text/plain":
  180. e.Text = p.body
  181. case ct == "text/html":
  182. e.HTML = p.body
  183. }
  184. }
  185. return e, nil
  186. }
  187. // parseMIMEParts will recursively walk a MIME entity and return a []mime.Part containing
  188. // each (flattened) mime.Part found.
  189. // It is important to note that there are no limits to the number of recursions, so be
  190. // careful when parsing unknown MIME structures!
  191. func parseMIMEParts(hs textproto.MIMEHeader, b io.Reader) ([]*part, error) {
  192. var ps []*part
  193. // If no content type is given, set it to the default
  194. if _, ok := hs["Content-Type"]; !ok {
  195. hs.Set("Content-Type", defaultContentType)
  196. }
  197. ct, params, err := mime.ParseMediaType(hs.Get("Content-Type"))
  198. if err != nil {
  199. return ps, err
  200. }
  201. // If it's a multipart email, recursively parse the parts
  202. if strings.HasPrefix(ct, "multipart/") {
  203. if _, ok := params["boundary"]; !ok {
  204. return ps, ErrMissingBoundary
  205. }
  206. mr := multipart.NewReader(b, params["boundary"])
  207. for {
  208. var buf bytes.Buffer
  209. p, err := mr.NextPart()
  210. if err == io.EOF {
  211. break
  212. }
  213. if err != nil {
  214. return ps, err
  215. }
  216. if _, ok := p.Header["Content-Type"]; !ok {
  217. p.Header.Set("Content-Type", defaultContentType)
  218. }
  219. subct, _, err := mime.ParseMediaType(p.Header.Get("Content-Type"))
  220. if err != nil {
  221. return ps, err
  222. }
  223. if strings.HasPrefix(subct, "multipart/") {
  224. sps, err := parseMIMEParts(p.Header, p)
  225. if err != nil {
  226. return ps, err
  227. }
  228. ps = append(ps, sps...)
  229. } else {
  230. var reader io.Reader
  231. reader = p
  232. const cte = "Content-Transfer-Encoding"
  233. if p.Header.Get(cte) == "base64" {
  234. reader = base64.NewDecoder(base64.StdEncoding, reader)
  235. }
  236. // Otherwise, just append the part to the list
  237. // Copy the part data into the buffer
  238. if _, err := io.Copy(&buf, reader); err != nil {
  239. return ps, err
  240. }
  241. ps = append(ps, &part{body: buf.Bytes(), header: p.Header})
  242. }
  243. }
  244. } else {
  245. // If it is not a multipart email, parse the body content as a single "part"
  246. if hs.Get("Content-Transfer-Encoding") == "quoted-printable" {
  247. b = quotedprintable.NewReader(b)
  248. }
  249. var buf bytes.Buffer
  250. if _, err := io.Copy(&buf, b); err != nil {
  251. return ps, err
  252. }
  253. ps = append(ps, &part{body: buf.Bytes(), header: hs})
  254. }
  255. return ps, nil
  256. }
  257. // Attach is used to attach content from an io.Reader to the email.
  258. // Required parameters include an io.Reader, the desired filename for the attachment, and the Content-Type
  259. // The function will return the created Attachment for reference, as well as nil for the error, if successful.
  260. func (e *Email) Attach(r io.Reader, filename string, c string) (a *Attachment, err error) {
  261. var buffer bytes.Buffer
  262. if _, err = io.Copy(&buffer, r); err != nil {
  263. return
  264. }
  265. at := &Attachment{
  266. Filename: filename,
  267. Header: textproto.MIMEHeader{},
  268. Content: buffer.Bytes(),
  269. }
  270. if c != "" {
  271. at.Header.Set("Content-Type", c)
  272. } else {
  273. at.Header.Set("Content-Type", "application/octet-stream")
  274. }
  275. at.Header.Set("Content-Disposition", fmt.Sprintf("attachment;\r\n filename=\"%s\"", filename))
  276. at.Header.Set("Content-ID", fmt.Sprintf("<%s>", filename))
  277. at.Header.Set("Content-Transfer-Encoding", "base64")
  278. e.Attachments = append(e.Attachments, at)
  279. return at, nil
  280. }
  281. // AttachFile is used to attach content to the email.
  282. // It attempts to open the file referenced by filename and, if successful, creates an Attachment.
  283. // This Attachment is then appended to the slice of Email.Attachments.
  284. // The function will then return the Attachment for reference, as well as nil for the error, if successful.
  285. func (e *Email) AttachFile(filename string) (a *Attachment, err error) {
  286. f, err := os.Open(filename)
  287. if err != nil {
  288. return
  289. }
  290. defer f.Close()
  291. ct := mime.TypeByExtension(filepath.Ext(filename))
  292. basename := filepath.Base(filename)
  293. return e.Attach(f, basename, ct)
  294. }
  295. // msgHeaders merges the Email's various fields and custom headers together in a
  296. // standards compliant way to create a MIMEHeader to be used in the resulting
  297. // message. It does not alter e.Headers.
  298. //
  299. // "e"'s fields To, Cc, From, Subject will be used unless they are present in
  300. // e.Headers. Unless set in e.Headers, "Date" will filled with the current time.
  301. func (e *Email) msgHeaders() (textproto.MIMEHeader, error) {
  302. res := make(textproto.MIMEHeader, len(e.Headers)+6)
  303. if e.Headers != nil {
  304. for _, h := range []string{"Reply-To", "To", "Cc", "From", "Subject", "Date", "Message-Id", "MIME-Version"} {
  305. if v, ok := e.Headers[h]; ok {
  306. res[h] = v
  307. }
  308. }
  309. }
  310. // Set headers if there are values.
  311. if _, ok := res["Reply-To"]; !ok && len(e.ReplyTo) > 0 {
  312. res.Set("Reply-To", strings.Join(e.ReplyTo, ", "))
  313. }
  314. if _, ok := res["To"]; !ok && len(e.To) > 0 {
  315. res.Set("To", strings.Join(e.To, ", "))
  316. }
  317. if _, ok := res["Cc"]; !ok && len(e.Cc) > 0 {
  318. res.Set("Cc", strings.Join(e.Cc, ", "))
  319. }
  320. if _, ok := res["Subject"]; !ok && e.Subject != "" {
  321. res.Set("Subject", e.Subject)
  322. }
  323. if _, ok := res["Message-Id"]; !ok {
  324. id, err := generateMessageID()
  325. if err != nil {
  326. return nil, err
  327. }
  328. res.Set("Message-Id", id)
  329. }
  330. // Date and From are required headers.
  331. if _, ok := res["From"]; !ok {
  332. res.Set("From", e.From)
  333. }
  334. if _, ok := res["Date"]; !ok {
  335. res.Set("Date", time.Now().Format(time.RFC1123Z))
  336. }
  337. if _, ok := res["MIME-Version"]; !ok {
  338. res.Set("MIME-Version", "1.0")
  339. }
  340. for field, vals := range e.Headers {
  341. if _, ok := res[field]; !ok {
  342. res[field] = vals
  343. }
  344. }
  345. return res, nil
  346. }
  347. func writeMessage(buff io.Writer, msg []byte, multipart bool, mediaType string, w *multipart.Writer) error {
  348. if multipart {
  349. header := textproto.MIMEHeader{
  350. "Content-Type": {mediaType + "; charset=UTF-8"},
  351. "Content-Transfer-Encoding": {"quoted-printable"},
  352. }
  353. if _, err := w.CreatePart(header); err != nil {
  354. return err
  355. }
  356. }
  357. qp := quotedprintable.NewWriter(buff)
  358. // Write the text
  359. if _, err := qp.Write(msg); err != nil {
  360. return err
  361. }
  362. return qp.Close()
  363. }
  364. func (e *Email) categorizeAttachments() (htmlRelated, others []*Attachment) {
  365. for _, a := range e.Attachments {
  366. if a.HTMLRelated {
  367. htmlRelated = append(htmlRelated, a)
  368. } else {
  369. others = append(others, a)
  370. }
  371. }
  372. return
  373. }
  374. // Bytes converts the Email object to a []byte representation, including all needed MIMEHeaders, boundaries, etc.
  375. func (e *Email) Bytes() ([]byte, error) {
  376. // TODO: better guess buffer size
  377. buff := bytes.NewBuffer(make([]byte, 0, 4096))
  378. headers, err := e.msgHeaders()
  379. if err != nil {
  380. return nil, err
  381. }
  382. htmlAttachments, otherAttachments := e.categorizeAttachments()
  383. if len(e.HTML) == 0 && len(htmlAttachments) > 0 {
  384. return nil, errors.New("there are HTML attachments, but no HTML body")
  385. }
  386. var (
  387. isMixed = len(otherAttachments) > 0
  388. isAlternative = len(e.Text) > 0 && len(e.HTML) > 0
  389. )
  390. var w *multipart.Writer
  391. if isMixed || isAlternative {
  392. w = multipart.NewWriter(buff)
  393. }
  394. switch {
  395. case isMixed:
  396. headers.Set("Content-Type", "multipart/mixed;\r\n boundary="+w.Boundary())
  397. case isAlternative:
  398. headers.Set("Content-Type", "multipart/alternative;\r\n boundary="+w.Boundary())
  399. case len(e.HTML) > 0:
  400. headers.Set("Content-Type", "text/html; charset=UTF-8")
  401. headers.Set("Content-Transfer-Encoding", "quoted-printable")
  402. default:
  403. headers.Set("Content-Type", "text/plain; charset=UTF-8")
  404. headers.Set("Content-Transfer-Encoding", "quoted-printable")
  405. }
  406. headerToBytes(buff, headers)
  407. _, err = io.WriteString(buff, "\r\n")
  408. if err != nil {
  409. return nil, err
  410. }
  411. // Check to see if there is a Text or HTML field
  412. if len(e.Text) > 0 || len(e.HTML) > 0 {
  413. var subWriter *multipart.Writer
  414. if isMixed && isAlternative {
  415. // Create the multipart alternative part
  416. subWriter = multipart.NewWriter(buff)
  417. header := textproto.MIMEHeader{
  418. "Content-Type": {"multipart/alternative;\r\n boundary=" + subWriter.Boundary()},
  419. }
  420. if _, err := w.CreatePart(header); err != nil {
  421. return nil, err
  422. }
  423. } else {
  424. subWriter = w
  425. }
  426. // Create the body sections
  427. if len(e.Text) > 0 {
  428. // Write the text
  429. if err := writeMessage(buff, e.Text, isMixed || isAlternative, "text/plain", subWriter); err != nil {
  430. return nil, err
  431. }
  432. }
  433. if len(e.HTML) > 0 {
  434. messageWriter := subWriter
  435. var relatedWriter *multipart.Writer
  436. if len(htmlAttachments) > 0 {
  437. relatedWriter = multipart.NewWriter(buff)
  438. header := textproto.MIMEHeader{
  439. "Content-Type": {"multipart/related;\r\n boundary=" + relatedWriter.Boundary()},
  440. }
  441. if _, err := subWriter.CreatePart(header); err != nil {
  442. return nil, err
  443. }
  444. messageWriter = relatedWriter
  445. }
  446. // Write the HTML
  447. if err := writeMessage(buff, e.HTML, isMixed || isAlternative, "text/html", messageWriter); err != nil {
  448. return nil, err
  449. }
  450. if len(htmlAttachments) > 0 {
  451. for _, a := range htmlAttachments {
  452. ap, err := relatedWriter.CreatePart(a.Header)
  453. if err != nil {
  454. return nil, err
  455. }
  456. // Write the base64Wrapped content to the part
  457. base64Wrap(ap, a.Content)
  458. }
  459. relatedWriter.Close()
  460. }
  461. }
  462. if isMixed && isAlternative {
  463. if err := subWriter.Close(); err != nil {
  464. return nil, err
  465. }
  466. }
  467. }
  468. // Create attachment part, if necessary
  469. for _, a := range otherAttachments {
  470. ap, err := w.CreatePart(a.Header)
  471. if err != nil {
  472. return nil, err
  473. }
  474. // Write the base64Wrapped content to the part
  475. base64Wrap(ap, a.Content)
  476. }
  477. if isMixed || isAlternative {
  478. if err := w.Close(); err != nil {
  479. return nil, err
  480. }
  481. }
  482. return buff.Bytes(), nil
  483. }
  484. // Send an email using the given host and SMTP auth (optional), returns any error thrown by smtp.SendMail
  485. // This function merges the To, Cc, and Bcc fields and calls the smtp.SendMail function using the Email.Bytes() output as the message
  486. func (e *Email) Send(addr string, a smtp.Auth) error {
  487. // Merge the To, Cc, and Bcc fields
  488. to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
  489. to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
  490. for i := 0; i < len(to); i++ {
  491. addr, err := mail.ParseAddress(to[i])
  492. if err != nil {
  493. return err
  494. }
  495. to[i] = addr.Address
  496. }
  497. // Check to make sure there is at least one recipient and one "From" address
  498. if e.From == "" || len(to) == 0 {
  499. return errors.New("Must specify at least one From address and one To address")
  500. }
  501. sender, err := e.parseSender()
  502. if err != nil {
  503. return err
  504. }
  505. raw, err := e.Bytes()
  506. if err != nil {
  507. return err
  508. }
  509. return smtp.SendMail(addr, a, sender, to, raw)
  510. }
  511. // Select and parse an SMTP envelope sender address. Choose Email.Sender if set, or fallback to Email.From.
  512. func (e *Email) parseSender() (string, error) {
  513. if e.Sender != "" {
  514. sender, err := mail.ParseAddress(e.Sender)
  515. if err != nil {
  516. return "", err
  517. }
  518. return sender.Address, nil
  519. } else {
  520. from, err := mail.ParseAddress(e.From)
  521. if err != nil {
  522. return "", err
  523. }
  524. return from.Address, nil
  525. }
  526. }
  527. // SendWithTLS sends an email over tls with an optional TLS config.
  528. //
  529. // The TLS Config is helpful if you need to connect to a host that is used an untrusted
  530. // certificate.
  531. func (e *Email) SendWithTLS(addr string, a smtp.Auth, t *tls.Config) error {
  532. // Merge the To, Cc, and Bcc fields
  533. to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
  534. to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
  535. for i := 0; i < len(to); i++ {
  536. addr, err := mail.ParseAddress(to[i])
  537. if err != nil {
  538. return err
  539. }
  540. to[i] = addr.Address
  541. }
  542. // Check to make sure there is at least one recipient and one "From" address
  543. if e.From == "" || len(to) == 0 {
  544. return errors.New("Must specify at least one From address and one To address")
  545. }
  546. sender, err := e.parseSender()
  547. if err != nil {
  548. return err
  549. }
  550. raw, err := e.Bytes()
  551. if err != nil {
  552. return err
  553. }
  554. conn, err := tls.Dial("tcp", addr, t)
  555. if err != nil {
  556. return err
  557. }
  558. c, err := smtp.NewClient(conn, t.ServerName)
  559. if err != nil {
  560. return err
  561. }
  562. defer c.Close()
  563. if err = c.Hello("localhost"); err != nil {
  564. return err
  565. }
  566. if a != nil {
  567. if ok, _ := c.Extension("AUTH"); ok {
  568. if err = c.Auth(a); err != nil {
  569. return err
  570. }
  571. }
  572. }
  573. if err = c.Mail(sender); err != nil {
  574. return err
  575. }
  576. for _, addr := range to {
  577. if err = c.Rcpt(addr); err != nil {
  578. return err
  579. }
  580. }
  581. w, err := c.Data()
  582. if err != nil {
  583. return err
  584. }
  585. _, err = w.Write(raw)
  586. if err != nil {
  587. return err
  588. }
  589. err = w.Close()
  590. if err != nil {
  591. return err
  592. }
  593. return c.Quit()
  594. }
  595. // SendWithStartTLS sends an email over TLS using STARTTLS with an optional TLS config.
  596. //
  597. // The TLS Config is helpful if you need to connect to a host that is used an untrusted
  598. // certificate.
  599. func (e *Email) SendWithStartTLS(addr string, a smtp.Auth, t *tls.Config) error {
  600. // Merge the To, Cc, and Bcc fields
  601. to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
  602. to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
  603. for i := 0; i < len(to); i++ {
  604. addr, err := mail.ParseAddress(to[i])
  605. if err != nil {
  606. return err
  607. }
  608. to[i] = addr.Address
  609. }
  610. // Check to make sure there is at least one recipient and one "From" address
  611. if e.From == "" || len(to) == 0 {
  612. return errors.New("Must specify at least one From address and one To address")
  613. }
  614. sender, err := e.parseSender()
  615. if err != nil {
  616. return err
  617. }
  618. raw, err := e.Bytes()
  619. if err != nil {
  620. return err
  621. }
  622. // Taken from the standard library
  623. // https://github.com/golang/go/blob/master/src/net/smtp/smtp.go#L328
  624. c, err := smtp.Dial(addr)
  625. if err != nil {
  626. return err
  627. }
  628. defer c.Close()
  629. if err = c.Hello("localhost"); err != nil {
  630. return err
  631. }
  632. // Use TLS if available
  633. if ok, _ := c.Extension("STARTTLS"); ok {
  634. if err = c.StartTLS(t); err != nil {
  635. return err
  636. }
  637. }
  638. if a != nil {
  639. if ok, _ := c.Extension("AUTH"); ok {
  640. if err = c.Auth(a); err != nil {
  641. return err
  642. }
  643. }
  644. }
  645. if err = c.Mail(sender); err != nil {
  646. return err
  647. }
  648. for _, addr := range to {
  649. if err = c.Rcpt(addr); err != nil {
  650. return err
  651. }
  652. }
  653. w, err := c.Data()
  654. if err != nil {
  655. return err
  656. }
  657. _, err = w.Write(raw)
  658. if err != nil {
  659. return err
  660. }
  661. err = w.Close()
  662. if err != nil {
  663. return err
  664. }
  665. return c.Quit()
  666. }
  667. // Attachment is a struct representing an email attachment.
  668. // Based on the mime/multipart.FileHeader struct, Attachment contains the name, MIMEHeader, and content of the attachment in question
  669. type Attachment struct {
  670. Filename string
  671. Header textproto.MIMEHeader
  672. Content []byte
  673. HTMLRelated bool
  674. }
  675. // base64Wrap encodes the attachment content, and wraps it according to RFC 2045 standards (every 76 chars)
  676. // The output is then written to the specified io.Writer
  677. func base64Wrap(w io.Writer, b []byte) {
  678. // 57 raw bytes per 76-byte base64 line.
  679. const maxRaw = 57
  680. // Buffer for each line, including trailing CRLF.
  681. buffer := make([]byte, MaxLineLength+len("\r\n"))
  682. copy(buffer[MaxLineLength:], "\r\n")
  683. // Process raw chunks until there's no longer enough to fill a line.
  684. for len(b) >= maxRaw {
  685. base64.StdEncoding.Encode(buffer, b[:maxRaw])
  686. w.Write(buffer)
  687. b = b[maxRaw:]
  688. }
  689. // Handle the last chunk of bytes.
  690. if len(b) > 0 {
  691. out := buffer[:base64.StdEncoding.EncodedLen(len(b))]
  692. base64.StdEncoding.Encode(out, b)
  693. out = append(out, "\r\n"...)
  694. w.Write(out)
  695. }
  696. }
  697. // headerToBytes renders "header" to "buff". If there are multiple values for a
  698. // field, multiple "Field: value\r\n" lines will be emitted.
  699. func headerToBytes(buff io.Writer, header textproto.MIMEHeader) {
  700. for field, vals := range header {
  701. for _, subval := range vals {
  702. // bytes.Buffer.Write() never returns an error.
  703. io.WriteString(buff, field)
  704. io.WriteString(buff, ": ")
  705. // Write the encoded header if needed
  706. switch {
  707. case field == "Content-Type" || field == "Content-Disposition":
  708. buff.Write([]byte(subval))
  709. case field == "From" || field == "To" || field == "Cc" || field == "Bcc":
  710. participants := strings.Split(subval, ",")
  711. for i, v := range participants {
  712. addr, err := mail.ParseAddress(v)
  713. if err != nil {
  714. continue
  715. }
  716. if addr.Name != "" {
  717. participants[i] = fmt.Sprintf("%s <%s>", mime.QEncoding.Encode("UTF-8", addr.Name), addr.Address)
  718. }
  719. }
  720. buff.Write([]byte(strings.Join(participants, ", ")))
  721. default:
  722. buff.Write([]byte(mime.QEncoding.Encode("UTF-8", subval)))
  723. }
  724. io.WriteString(buff, "\r\n")
  725. }
  726. }
  727. }
  728. var maxBigInt = big.NewInt(math.MaxInt64)
  729. // generateMessageID generates and returns a string suitable for an RFC 2822
  730. // compliant Message-ID, e.g.:
  731. // <1444789264909237300.3464.1819418242800517193@DESKTOP01>
  732. //
  733. // The following parameters are used to generate a Message-ID:
  734. // - The nanoseconds since Epoch
  735. // - The calling PID
  736. // - A cryptographically random int64
  737. // - The sending hostname
  738. func generateMessageID() (string, error) {
  739. t := time.Now().UnixNano()
  740. pid := os.Getpid()
  741. rint, err := rand.Int(rand.Reader, maxBigInt)
  742. if err != nil {
  743. return "", err
  744. }
  745. h, err := os.Hostname()
  746. // If we can't get the hostname, we'll use localhost
  747. if err != nil {
  748. h = "localhost.localdomain"
  749. }
  750. msgid := fmt.Sprintf("<%d.%d.%d@%s>", t, pid, rint, h)
  751. return msgid, nil
  752. }