email_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. package email
  2. import (
  3. "testing"
  4. "bytes"
  5. "crypto/rand"
  6. "io"
  7. "io/ioutil"
  8. "mime"
  9. "mime/multipart"
  10. "mime/quotedprintable"
  11. "net/mail"
  12. "net/smtp"
  13. "net/textproto"
  14. )
  15. func prepareEmail() *Email {
  16. e := NewEmail()
  17. e.From = "Jordan Wright <test@example.com>"
  18. e.To = []string{"test@example.com"}
  19. e.Bcc = []string{"test_bcc@example.com"}
  20. e.Cc = []string{"test_cc@example.com"}
  21. e.Subject = "Awesome Subject"
  22. return e
  23. }
  24. func basicTests(t *testing.T, e *Email) *mail.Message {
  25. raw, err := e.Bytes()
  26. if err != nil {
  27. t.Fatal("Failed to render message: ", e)
  28. }
  29. msg, err := mail.ReadMessage(bytes.NewBuffer(raw))
  30. if err != nil {
  31. t.Fatal("Could not parse rendered message: ", err)
  32. }
  33. expectedHeaders := map[string]string{
  34. "To": "test@example.com",
  35. "From": "Jordan Wright <test@example.com>",
  36. "Cc": "test_cc@example.com",
  37. "Subject": "Awesome Subject",
  38. }
  39. for header, expected := range expectedHeaders {
  40. if val := msg.Header.Get(header); val != expected {
  41. t.Errorf("Wrong value for message header %s: %v != %v", header, expected, val)
  42. }
  43. }
  44. return msg
  45. }
  46. func TestEmailText(t *testing.T) {
  47. e := prepareEmail()
  48. e.Text = []byte("Text Body is, of course, supported!\n")
  49. msg := basicTests(t, e)
  50. // Were the right headers set?
  51. ct := msg.Header.Get("Content-type")
  52. mt, _, err := mime.ParseMediaType(ct)
  53. if err != nil {
  54. t.Fatal("Content-type header is invalid: ", ct)
  55. } else if mt != "text/plain" {
  56. t.Fatalf("Content-type expected \"text/plain\", not %v", mt)
  57. }
  58. }
  59. func TestEmailHTML(t *testing.T) {
  60. e := prepareEmail()
  61. e.HTML = []byte("<h1>Fancy Html is supported, too!</h1>\n")
  62. msg := basicTests(t, e)
  63. // Were the right headers set?
  64. ct := msg.Header.Get("Content-type")
  65. mt, _, err := mime.ParseMediaType(ct)
  66. if err != nil {
  67. t.Fatal("Content-type header is invalid: ", ct)
  68. } else if mt != "text/html" {
  69. t.Fatalf("Content-type expected \"text/html\", not %v", mt)
  70. }
  71. }
  72. func TestEmailTextAttachment(t *testing.T) {
  73. e := prepareEmail()
  74. e.Text = []byte("Text Body is, of course, supported!\n")
  75. _, err := e.Attach(bytes.NewBufferString("Rad attachment"), "rad.txt", "text/plain; charset=utf-8")
  76. if err != nil {
  77. t.Fatal("Could not add an attachment to the message: ", err)
  78. }
  79. msg := basicTests(t, e)
  80. // Were the right headers set?
  81. ct := msg.Header.Get("Content-type")
  82. mt, params, err := mime.ParseMediaType(ct)
  83. if err != nil {
  84. t.Fatal("Content-type header is invalid: ", ct)
  85. } else if mt != "multipart/mixed" {
  86. t.Fatalf("Content-type expected \"multipart/mixed\", not %v", mt)
  87. }
  88. b := params["boundary"]
  89. if b == "" {
  90. t.Fatalf("Invalid or missing boundary parameter: ", b)
  91. }
  92. if len(params) != 1 {
  93. t.Fatal("Unexpected content-type parameters")
  94. }
  95. // Is the generated message parsable?
  96. mixed := multipart.NewReader(msg.Body, params["boundary"])
  97. text, err := mixed.NextPart()
  98. if err != nil {
  99. t.Fatalf("Could not find text component of email: ", err)
  100. }
  101. // Does the text portion match what we expect?
  102. mt, _, err = mime.ParseMediaType(text.Header.Get("Content-type"))
  103. if err != nil {
  104. t.Fatal("Could not parse message's Content-Type")
  105. } else if mt != "text/plain" {
  106. t.Fatal("Message missing text/plain")
  107. }
  108. plainText, err := ioutil.ReadAll(text)
  109. if err != nil {
  110. t.Fatal("Could not read plain text component of message: ", err)
  111. }
  112. if !bytes.Equal(plainText, []byte("Text Body is, of course, supported!\r\n")) {
  113. t.Fatalf("Plain text is broken: %#q", plainText)
  114. }
  115. // Check attachments.
  116. _, err = mixed.NextPart()
  117. if err != nil {
  118. t.Fatalf("Could not find attachment component of email: ", err)
  119. }
  120. if _, err = mixed.NextPart(); err != io.EOF {
  121. t.Error("Expected only text and one attachment!")
  122. }
  123. }
  124. func TestEmailTextHtmlAttachment(t *testing.T) {
  125. e := prepareEmail()
  126. e.Text = []byte("Text Body is, of course, supported!\n")
  127. e.HTML = []byte("<h1>Fancy Html is supported, too!</h1>\n")
  128. _, err := e.Attach(bytes.NewBufferString("Rad attachment"), "rad.txt", "text/plain; charset=utf-8")
  129. if err != nil {
  130. t.Fatal("Could not add an attachment to the message: ", err)
  131. }
  132. msg := basicTests(t, e)
  133. // Were the right headers set?
  134. ct := msg.Header.Get("Content-type")
  135. mt, params, err := mime.ParseMediaType(ct)
  136. if err != nil {
  137. t.Fatal("Content-type header is invalid: ", ct)
  138. } else if mt != "multipart/mixed" {
  139. t.Fatalf("Content-type expected \"multipart/mixed\", not %v", mt)
  140. }
  141. b := params["boundary"]
  142. if b == "" {
  143. t.Fatalf("Invalid or missing boundary parameter: ", b)
  144. }
  145. if len(params) != 1 {
  146. t.Fatal("Unexpected content-type parameters")
  147. }
  148. // Is the generated message parsable?
  149. mixed := multipart.NewReader(msg.Body, params["boundary"])
  150. text, err := mixed.NextPart()
  151. if err != nil {
  152. t.Fatalf("Could not find text component of email: ", err)
  153. }
  154. // Does the text portion match what we expect?
  155. mt, params, err = mime.ParseMediaType(text.Header.Get("Content-type"))
  156. if err != nil {
  157. t.Fatal("Could not parse message's Content-Type")
  158. } else if mt != "multipart/alternative" {
  159. t.Fatal("Message missing multipart/alternative")
  160. }
  161. mpReader := multipart.NewReader(text, params["boundary"])
  162. part, err := mpReader.NextPart()
  163. if err != nil {
  164. t.Fatal("Could not read plain text component of message: ", err)
  165. }
  166. plainText, err := ioutil.ReadAll(part)
  167. if err != nil {
  168. t.Fatal("Could not read plain text component of message: ", err)
  169. }
  170. if !bytes.Equal(plainText, []byte("Text Body is, of course, supported!\r\n")) {
  171. t.Fatalf("Plain text is broken: %#q", plainText)
  172. }
  173. // Check attachments.
  174. _, err = mixed.NextPart()
  175. if err != nil {
  176. t.Fatalf("Could not find attachment component of email: ", err)
  177. }
  178. if _, err = mixed.NextPart(); err != io.EOF {
  179. t.Error("Expected only text and one attachment!")
  180. }
  181. }
  182. func TestEmailAttachment(t *testing.T) {
  183. e := prepareEmail()
  184. _, err := e.Attach(bytes.NewBufferString("Rad attachment"), "rad.txt", "text/plain; charset=utf-8")
  185. if err != nil {
  186. t.Fatal("Could not add an attachment to the message: ", err)
  187. }
  188. msg := basicTests(t, e)
  189. // Were the right headers set?
  190. ct := msg.Header.Get("Content-type")
  191. mt, params, err := mime.ParseMediaType(ct)
  192. if err != nil {
  193. t.Fatal("Content-type header is invalid: ", ct)
  194. } else if mt != "multipart/mixed" {
  195. t.Fatalf("Content-type expected \"multipart/mixed\", not %v", mt)
  196. }
  197. b := params["boundary"]
  198. if b == "" {
  199. t.Fatalf("Invalid or missing boundary parameter: ", b)
  200. }
  201. if len(params) != 1 {
  202. t.Fatal("Unexpected content-type parameters")
  203. }
  204. // Is the generated message parsable?
  205. mixed := multipart.NewReader(msg.Body, params["boundary"])
  206. // Check attachments.
  207. _, err = mixed.NextPart()
  208. if err != nil {
  209. t.Fatalf("Could not find attachment component of email: ", err)
  210. }
  211. if _, err = mixed.NextPart(); err != io.EOF {
  212. t.Error("Expected only one attachment!")
  213. }
  214. }
  215. func TestEmailFromReader(t *testing.T) {
  216. ex := &Email{
  217. Subject: "Test Subject",
  218. To: []string{"Jordan Wright <jmwright798@gmail.com>"},
  219. From: "Jordan Wright <jmwright798@gmail.com>",
  220. Text: []byte("This is a test email with HTML Formatting. It also has very long lines so\nthat the content must be wrapped if using quoted-printable decoding.\n"),
  221. HTML: []byte("<div dir=\"ltr\">This is a test email with <b>HTML Formatting.</b>\u00a0It also has very long lines so that the content must be wrapped if using quoted-printable decoding.</div>\n"),
  222. }
  223. raw := []byte(`
  224. MIME-Version: 1.0
  225. Subject: Test Subject
  226. From: Jordan Wright <jmwright798@gmail.com>
  227. To: Jordan Wright <jmwright798@gmail.com>
  228. Content-Type: multipart/alternative; boundary=001a114fb3fc42fd6b051f834280
  229. --001a114fb3fc42fd6b051f834280
  230. Content-Type: text/plain; charset=UTF-8
  231. This is a test email with HTML Formatting. It also has very long lines so
  232. that the content must be wrapped if using quoted-printable decoding.
  233. --001a114fb3fc42fd6b051f834280
  234. Content-Type: text/html; charset=UTF-8
  235. Content-Transfer-Encoding: quoted-printable
  236. <div dir=3D"ltr">This is a test email with <b>HTML Formatting.</b>=C2=A0It =
  237. also has very long lines so that the content must be wrapped if using quote=
  238. d-printable decoding.</div>
  239. --001a114fb3fc42fd6b051f834280--`)
  240. e, err := NewEmailFromReader(bytes.NewReader(raw))
  241. if err != nil {
  242. t.Fatalf("Error creating email %s", err.Error())
  243. }
  244. if e.Subject != ex.Subject {
  245. t.Fatalf("Incorrect subject. %#q != %#q", e.Subject, ex.Subject)
  246. }
  247. if !bytes.Equal(e.Text, ex.Text) {
  248. t.Fatalf("Incorrect text: %#q != %#q", e.Text, ex.Text)
  249. }
  250. if !bytes.Equal(e.HTML, ex.HTML) {
  251. t.Fatalf("Incorrect HTML: %#q != %#q", e.HTML, ex.HTML)
  252. }
  253. if e.From != ex.From {
  254. t.Fatalf("Incorrect \"From\": %#q != %#q", e.From, ex.From)
  255. }
  256. }
  257. func TestNonMultipartEmailFromReader(t *testing.T) {
  258. ex := &Email{
  259. Text: []byte("This is a test message!"),
  260. Subject: "Example Subject (no MIME Type)",
  261. Headers: textproto.MIMEHeader{},
  262. }
  263. ex.Headers.Add("Content-Type", "text/plain; charset=us-ascii")
  264. ex.Headers.Add("Message-ID", "<foobar@example.com>")
  265. raw := []byte(`From: "Foo Bar" <foobar@example.com>
  266. Content-Type: text/plain
  267. To: foobar@example.com
  268. Subject: Example Subject (no MIME Type)
  269. Message-ID: <foobar@example.com>
  270. This is a test message!`)
  271. e, err := NewEmailFromReader(bytes.NewReader(raw))
  272. if err != nil {
  273. t.Fatalf("Error creating email %s", err.Error())
  274. }
  275. if ex.Subject != e.Subject {
  276. t.Errorf("Incorrect subject. %#q != %#q\n", ex.Subject, e.Subject)
  277. }
  278. if !bytes.Equal(ex.Text, e.Text) {
  279. t.Errorf("Incorrect body. %#q != %#q\n", ex.Text, e.Text)
  280. }
  281. if ex.Headers.Get("Message-ID") != e.Headers.Get("Message-ID") {
  282. t.Errorf("Incorrect message ID. %#q != %#q\n", ex.Headers.Get("Message-ID"), e.Headers.Get("Message-ID"))
  283. }
  284. }
  285. func ExampleGmail() {
  286. e := NewEmail()
  287. e.From = "Jordan Wright <test@gmail.com>"
  288. e.To = []string{"test@example.com"}
  289. e.Bcc = []string{"test_bcc@example.com"}
  290. e.Cc = []string{"test_cc@example.com"}
  291. e.Subject = "Awesome Subject"
  292. e.Text = []byte("Text Body is, of course, supported!\n")
  293. e.HTML = []byte("<h1>Fancy Html is supported, too!</h1>\n")
  294. e.Send("smtp.gmail.com:587", smtp.PlainAuth("", e.From, "password123", "smtp.gmail.com"))
  295. }
  296. func ExampleAttach() {
  297. e := NewEmail()
  298. e.AttachFile("test.txt")
  299. }
  300. func Test_base64Wrap(t *testing.T) {
  301. file := "I'm a file long enough to force the function to wrap a\n" +
  302. "couple of lines, but I stop short of the end of one line and\n" +
  303. "have some padding dangling at the end."
  304. encoded := "SSdtIGEgZmlsZSBsb25nIGVub3VnaCB0byBmb3JjZSB0aGUgZnVuY3Rpb24gdG8gd3JhcCBhCmNv\r\n" +
  305. "dXBsZSBvZiBsaW5lcywgYnV0IEkgc3RvcCBzaG9ydCBvZiB0aGUgZW5kIG9mIG9uZSBsaW5lIGFu\r\n" +
  306. "ZApoYXZlIHNvbWUgcGFkZGluZyBkYW5nbGluZyBhdCB0aGUgZW5kLg==\r\n"
  307. var buf bytes.Buffer
  308. base64Wrap(&buf, []byte(file))
  309. if !bytes.Equal(buf.Bytes(), []byte(encoded)) {
  310. t.Fatalf("Encoded file does not match expected: %#q != %#q", string(buf.Bytes()), encoded)
  311. }
  312. }
  313. // *Since the mime library in use by ```email``` is now in the stdlib, this test is deprecated
  314. func Test_quotedPrintEncode(t *testing.T) {
  315. var buf bytes.Buffer
  316. text := []byte("Dear reader!\n\n" +
  317. "This is a test email to try and capture some of the corner cases that exist within\n" +
  318. "the quoted-printable encoding.\n" +
  319. "There are some wacky parts like =, and this input assumes UNIX line breaks so\r\n" +
  320. "it can come out a little weird. Also, we need to support unicode so here's a fish: 🐟\n")
  321. expected := []byte("Dear reader!\r\n\r\n" +
  322. "This is a test email to try and capture some of the corner cases that exist=\r\n" +
  323. " within\r\n" +
  324. "the quoted-printable encoding.\r\n" +
  325. "There are some wacky parts like =3D, and this input assumes UNIX line break=\r\n" +
  326. "s so\r\n" +
  327. "it can come out a little weird. Also, we need to support unicode so here's=\r\n" +
  328. " a fish: =F0=9F=90=9F\r\n")
  329. qp := quotedprintable.NewWriter(&buf)
  330. if _, err := qp.Write(text); err != nil {
  331. t.Fatal("quotePrintEncode: ", err)
  332. }
  333. if err := qp.Close(); err != nil {
  334. t.Fatal("Error closing writer", err)
  335. }
  336. if b := buf.Bytes(); !bytes.Equal(b, expected) {
  337. t.Errorf("quotedPrintEncode generated incorrect results: %#q != %#q", b, expected)
  338. }
  339. }
  340. func TestMultipartNoContentType(t *testing.T) {
  341. raw := []byte(`From: Mikhail Gusarov <dottedmag@dottedmag.net>
  342. To: notmuch@notmuchmail.org
  343. References: <20091117190054.GU3165@dottiness.seas.harvard.edu>
  344. Date: Wed, 18 Nov 2009 01:02:38 +0600
  345. Message-ID: <87iqd9rn3l.fsf@vertex.dottedmag>
  346. MIME-Version: 1.0
  347. Subject: Re: [notmuch] Working with Maildir storage?
  348. Content-Type: multipart/mixed; boundary="===============1958295626=="
  349. --===============1958295626==
  350. Content-Type: multipart/signed; boundary="=-=-=";
  351. micalg=pgp-sha1; protocol="application/pgp-signature"
  352. --=-=-=
  353. Content-Transfer-Encoding: quoted-printable
  354. Twas brillig at 14:00:54 17.11.2009 UTC-05 when lars@seas.harvard.edu did g=
  355. yre and gimble:
  356. --=-=-=
  357. Content-Type: application/pgp-signature
  358. -----BEGIN PGP SIGNATURE-----
  359. Version: GnuPG v1.4.9 (GNU/Linux)
  360. iQIcBAEBAgAGBQJLAvNOAAoJEJ0g9lA+M4iIjLYQAKp0PXEgl3JMOEBisH52AsIK
  361. =/ksP
  362. -----END PGP SIGNATURE-----
  363. --=-=-=--
  364. --===============1958295626==
  365. Content-Type: text/plain; charset="us-ascii"
  366. MIME-Version: 1.0
  367. Content-Transfer-Encoding: 7bit
  368. Content-Disposition: inline
  369. Testing!
  370. --===============1958295626==--
  371. `)
  372. e, err := NewEmailFromReader(bytes.NewReader(raw))
  373. if err != nil {
  374. t.Fatalf("Error when parsing email %s", err.Error())
  375. }
  376. if !bytes.Equal(e.Text, []byte("Testing!")) {
  377. t.Fatalf("Error incorrect text: %#q != %#q\n", e.Text, "Testing!")
  378. }
  379. }
  380. // *Since the mime library in use by ```email``` is now in the stdlib, this test is deprecated
  381. func Test_quotedPrintDecode(t *testing.T) {
  382. text := []byte("Dear reader!\r\n\r\n" +
  383. "This is a test email to try and capture some of the corner cases that exist=\r\n" +
  384. " within\r\n" +
  385. "the quoted-printable encoding.\r\n" +
  386. "There are some wacky parts like =3D, and this input assumes UNIX line break=\r\n" +
  387. "s so\r\n" +
  388. "it can come out a little weird. Also, we need to support unicode so here's=\r\n" +
  389. " a fish: =F0=9F=90=9F\r\n")
  390. expected := []byte("Dear reader!\r\n\r\n" +
  391. "This is a test email to try and capture some of the corner cases that exist within\r\n" +
  392. "the quoted-printable encoding.\r\n" +
  393. "There are some wacky parts like =, and this input assumes UNIX line breaks so\r\n" +
  394. "it can come out a little weird. Also, we need to support unicode so here's a fish: 🐟\r\n")
  395. qp := quotedprintable.NewReader(bytes.NewReader(text))
  396. got, err := ioutil.ReadAll(qp)
  397. if err != nil {
  398. t.Fatal("quotePrintDecode: ", err)
  399. }
  400. if !bytes.Equal(got, expected) {
  401. t.Errorf("quotedPrintDecode generated incorrect results: %#q != %#q", got, expected)
  402. }
  403. }
  404. func Benchmark_base64Wrap(b *testing.B) {
  405. // Reasonable base case; 128K random bytes
  406. file := make([]byte, 128*1024)
  407. if _, err := rand.Read(file); err != nil {
  408. panic(err)
  409. }
  410. for i := 0; i <= b.N; i++ {
  411. base64Wrap(ioutil.Discard, file)
  412. }
  413. }