email.go 22 KB

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