email_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 TestEmailTextHtmlAttachment(t *testing.T) {
  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. e.Text = []byte("Text Body is, of course, supported!\n")
  23. e.HTML = []byte("<h1>Fancy Html is supported, too!</h1>\n")
  24. e.Attach(bytes.NewBufferString("Rad attachement"), "rad.txt", "text/plain; charset=utf-8")
  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. // Were the right headers set?
  45. ct := msg.Header.Get("Content-type")
  46. mt, params, err := mime.ParseMediaType(ct)
  47. if err != nil {
  48. t.Fatal("Content-type header is invalid: ", ct)
  49. } else if mt != "multipart/mixed" {
  50. t.Fatalf("Content-type expected \"multipart/mixed\", not %v", mt)
  51. }
  52. b := params["boundary"]
  53. if b == "" {
  54. t.Fatalf("Invalid or missing boundary parameter: ", b)
  55. }
  56. if len(params) != 1 {
  57. t.Fatal("Unexpected content-type parameters")
  58. }
  59. // Is the generated message parsable?
  60. mixed := multipart.NewReader(msg.Body, params["boundary"])
  61. text, err := mixed.NextPart()
  62. if err != nil {
  63. t.Fatalf("Could not find text component of email: ", err)
  64. }
  65. // Does the text portion match what we expect?
  66. mt, params, err = mime.ParseMediaType(text.Header.Get("Content-type"))
  67. if err != nil {
  68. t.Fatal("Could not parse message's Content-Type")
  69. } else if mt != "multipart/alternative" {
  70. t.Fatal("Message missing multipart/alternative")
  71. }
  72. mpReader := multipart.NewReader(text, params["boundary"])
  73. part, err := mpReader.NextPart()
  74. if err != nil {
  75. t.Fatal("Could not read plain text component of message: ", err)
  76. }
  77. plainText, err := ioutil.ReadAll(part)
  78. if err != nil {
  79. t.Fatal("Could not read plain text component of message: ", err)
  80. }
  81. if !bytes.Equal(plainText, []byte("Text Body is, of course, supported!\r\n")) {
  82. t.Fatalf("Plain text is broken: %#q", plainText)
  83. }
  84. // Check attachments.
  85. _, err = mixed.NextPart()
  86. if err != nil {
  87. t.Fatalf("Could not find attachemnt compoenent of email: ", err)
  88. }
  89. if _, err = mixed.NextPart(); err != io.EOF {
  90. t.Error("Expected only text and one attachement!")
  91. }
  92. }
  93. func TestEmailFromReader(t *testing.T) {
  94. ex := &Email{
  95. Subject: "Test Subject",
  96. To: []string{"Jordan Wright <jmwright798@gmail.com>"},
  97. From: "Jordan Wright <jmwright798@gmail.com>",
  98. 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"),
  99. 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"),
  100. }
  101. raw := []byte(`MIME-Version: 1.0
  102. Subject: Test Subject
  103. From: Jordan Wright <jmwright798@gmail.com>
  104. To: Jordan Wright <jmwright798@gmail.com>
  105. Content-Type: multipart/alternative; boundary=001a114fb3fc42fd6b051f834280
  106. --001a114fb3fc42fd6b051f834280
  107. Content-Type: text/plain; charset=UTF-8
  108. This is a test email with HTML Formatting. It also has very long lines so
  109. that the content must be wrapped if using quoted-printable decoding.
  110. --001a114fb3fc42fd6b051f834280
  111. Content-Type: text/html; charset=UTF-8
  112. Content-Transfer-Encoding: quoted-printable
  113. <div dir=3D"ltr">This is a test email with <b>HTML Formatting.</b>=C2=A0It =
  114. also has very long lines so that the content must be wrapped if using quote=
  115. d-printable decoding.</div>
  116. --001a114fb3fc42fd6b051f834280--`)
  117. e, err := NewEmailFromReader(bytes.NewReader(raw))
  118. if err != nil {
  119. t.Fatalf("Error creating email %s", err.Error())
  120. }
  121. if e.Subject != ex.Subject {
  122. t.Fatalf("Incorrect subject. %#q != %#q", e.Subject, ex.Subject)
  123. }
  124. if !bytes.Equal(e.Text, ex.Text) {
  125. t.Fatalf("Incorrect text: %#q != %#q", e.Text, ex.Text)
  126. }
  127. if !bytes.Equal(e.HTML, ex.HTML) {
  128. t.Fatalf("Incorrect HTML: %#q != %#q", e.HTML, ex.HTML)
  129. }
  130. if e.From != ex.From {
  131. t.Fatalf("Incorrect \"From\": %#q != %#q", e.From, ex.From)
  132. }
  133. }
  134. func TestNonMultipartEmailFromReader(t *testing.T) {
  135. ex := &Email{
  136. Text: []byte("This is a test message!"),
  137. Subject: "Example Subject (no MIME Type)",
  138. Headers: textproto.MIMEHeader{},
  139. }
  140. ex.Headers.Add("Content-Type", "text/plain; charset=us-ascii")
  141. ex.Headers.Add("Message-ID", "<foobar@example.com>")
  142. raw := []byte(`From: "Foo Bar" <foobar@example.com>
  143. Content-Type: text/plain
  144. To: foobar@example.com
  145. Subject: Example Subject (no MIME Type)
  146. Message-ID: <foobar@example.com>
  147. This is a test message!`)
  148. e, err := NewEmailFromReader(bytes.NewReader(raw))
  149. if err != nil {
  150. t.Fatalf("Error creating email %s", err.Error())
  151. }
  152. if ex.Subject != e.Subject {
  153. t.Errorf("Incorrect subject. %#q != %#q\n", ex.Subject, e.Subject)
  154. }
  155. if !bytes.Equal(ex.Text, e.Text) {
  156. t.Errorf("Incorrect body. %#q != %#q\n", ex.Text, e.Text)
  157. }
  158. if ex.Headers.Get("Message-ID") != e.Headers.Get("Message-ID") {
  159. t.Errorf("Incorrect message ID. %#q != %#q\n", ex.Headers.Get("Message-ID"), e.Headers.Get("Message-ID"))
  160. }
  161. }
  162. func ExampleGmail() {
  163. e := NewEmail()
  164. e.From = "Jordan Wright <test@gmail.com>"
  165. e.To = []string{"test@example.com"}
  166. e.Bcc = []string{"test_bcc@example.com"}
  167. e.Cc = []string{"test_cc@example.com"}
  168. e.Subject = "Awesome Subject"
  169. e.Text = []byte("Text Body is, of course, supported!\n")
  170. e.HTML = []byte("<h1>Fancy Html is supported, too!</h1>\n")
  171. e.Send("smtp.gmail.com:587", smtp.PlainAuth("", e.From, "password123", "smtp.gmail.com"))
  172. }
  173. func ExampleAttach() {
  174. e := NewEmail()
  175. e.AttachFile("test.txt")
  176. }
  177. func Test_base64Wrap(t *testing.T) {
  178. file := "I'm a file long enough to force the function to wrap a\n" +
  179. "couple of lines, but I stop short of the end of one line and\n" +
  180. "have some padding dangling at the end."
  181. encoded := "SSdtIGEgZmlsZSBsb25nIGVub3VnaCB0byBmb3JjZSB0aGUgZnVuY3Rpb24gdG8gd3JhcCBhCmNv\r\n" +
  182. "dXBsZSBvZiBsaW5lcywgYnV0IEkgc3RvcCBzaG9ydCBvZiB0aGUgZW5kIG9mIG9uZSBsaW5lIGFu\r\n" +
  183. "ZApoYXZlIHNvbWUgcGFkZGluZyBkYW5nbGluZyBhdCB0aGUgZW5kLg==\r\n"
  184. var buf bytes.Buffer
  185. base64Wrap(&buf, []byte(file))
  186. if !bytes.Equal(buf.Bytes(), []byte(encoded)) {
  187. t.Fatalf("Encoded file does not match expected: %#q != %#q", string(buf.Bytes()), encoded)
  188. }
  189. }
  190. // *Since the mime library in use by ```email``` is now in the stdlib, this test is deprecated
  191. func Test_quotedPrintEncode(t *testing.T) {
  192. var buf bytes.Buffer
  193. text := []byte("Dear reader!\n\n" +
  194. "This is a test email to try and capture some of the corner cases that exist within\n" +
  195. "the quoted-printable encoding.\n" +
  196. "There are some wacky parts like =, and this input assumes UNIX line breaks so\r\n" +
  197. "it can come out a little weird. Also, we need to support unicode so here's a fish: 🐟\n")
  198. expected := []byte("Dear reader!\r\n\r\n" +
  199. "This is a test email to try and capture some of the corner cases that exist=\r\n" +
  200. " within\r\n" +
  201. "the quoted-printable encoding.\r\n" +
  202. "There are some wacky parts like =3D, and this input assumes UNIX line break=\r\n" +
  203. "s so\r\n" +
  204. "it can come out a little weird. Also, we need to support unicode so here's=\r\n" +
  205. " a fish: =F0=9F=90=9F\r\n")
  206. qp := quotedprintable.NewWriter(&buf)
  207. if _, err := qp.Write(text); err != nil {
  208. t.Fatal("quotePrintEncode: ", err)
  209. }
  210. if err := qp.Close(); err != nil {
  211. t.Fatal("Error closing writer", err)
  212. }
  213. if b := buf.Bytes(); !bytes.Equal(b, expected) {
  214. t.Errorf("quotedPrintEncode generated incorrect results: %#q != %#q", b, expected)
  215. }
  216. }
  217. func TestMultipartNoContentType(t *testing.T) {
  218. raw := []byte(`From: Mikhail Gusarov <dottedmag@dottedmag.net>
  219. To: notmuch@notmuchmail.org
  220. References: <20091117190054.GU3165@dottiness.seas.harvard.edu>
  221. Date: Wed, 18 Nov 2009 01:02:38 +0600
  222. Message-ID: <87iqd9rn3l.fsf@vertex.dottedmag>
  223. MIME-Version: 1.0
  224. Subject: Re: [notmuch] Working with Maildir storage?
  225. Content-Type: multipart/mixed; boundary="===============1958295626=="
  226. --===============1958295626==
  227. Content-Type: multipart/signed; boundary="=-=-=";
  228. micalg=pgp-sha1; protocol="application/pgp-signature"
  229. --=-=-=
  230. Content-Transfer-Encoding: quoted-printable
  231. Twas brillig at 14:00:54 17.11.2009 UTC-05 when lars@seas.harvard.edu did g=
  232. yre and gimble:
  233. --=-=-=
  234. Content-Type: application/pgp-signature
  235. -----BEGIN PGP SIGNATURE-----
  236. Version: GnuPG v1.4.9 (GNU/Linux)
  237. iQIcBAEBAgAGBQJLAvNOAAoJEJ0g9lA+M4iIjLYQAKp0PXEgl3JMOEBisH52AsIK
  238. =/ksP
  239. -----END PGP SIGNATURE-----
  240. --=-=-=--
  241. --===============1958295626==
  242. Content-Type: text/plain; charset="us-ascii"
  243. MIME-Version: 1.0
  244. Content-Transfer-Encoding: 7bit
  245. Content-Disposition: inline
  246. Testing!
  247. --===============1958295626==--
  248. `)
  249. e, err := NewEmailFromReader(bytes.NewReader(raw))
  250. if err != nil {
  251. t.Fatalf("Error when parsing email %s", err.Error())
  252. }
  253. }
  254. // *Since the mime library in use by ```email``` is now in the stdlib, this test is deprecated
  255. func Test_quotedPrintDecode(t *testing.T) {
  256. text := []byte("Dear reader!\r\n\r\n" +
  257. "This is a test email to try and capture some of the corner cases that exist=\r\n" +
  258. " within\r\n" +
  259. "the quoted-printable encoding.\r\n" +
  260. "There are some wacky parts like =3D, and this input assumes UNIX line break=\r\n" +
  261. "s so\r\n" +
  262. "it can come out a little weird. Also, we need to support unicode so here's=\r\n" +
  263. " a fish: =F0=9F=90=9F\r\n")
  264. expected := []byte("Dear reader!\r\n\r\n" +
  265. "This is a test email to try and capture some of the corner cases that exist within\r\n" +
  266. "the quoted-printable encoding.\r\n" +
  267. "There are some wacky parts like =, and this input assumes UNIX line breaks so\r\n" +
  268. "it can come out a little weird. Also, we need to support unicode so here's a fish: 🐟\r\n")
  269. qp := quotedprintable.NewReader(bytes.NewReader(text))
  270. got, err := ioutil.ReadAll(qp)
  271. if err != nil {
  272. t.Fatal("quotePrintDecode: ", err)
  273. }
  274. if !bytes.Equal(got, expected) {
  275. t.Errorf("quotedPrintDecode generated incorrect results: %#q != %#q", got, expected)
  276. }
  277. }
  278. func Benchmark_base64Wrap(b *testing.B) {
  279. // Reasonable base case; 128K random bytes
  280. file := make([]byte, 128*1024)
  281. if _, err := rand.Read(file); err != nil {
  282. panic(err)
  283. }
  284. for i := 0; i <= b.N; i++ {
  285. base64Wrap(ioutil.Discard, file)
  286. }
  287. }