email_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. package email
  2. import (
  3. "fmt"
  4. "strings"
  5. "testing"
  6. "bufio"
  7. "bytes"
  8. "crypto/rand"
  9. "io"
  10. "io/ioutil"
  11. "mime"
  12. "mime/multipart"
  13. "mime/quotedprintable"
  14. "net/mail"
  15. "net/smtp"
  16. "net/textproto"
  17. )
  18. func prepareEmail() *Email {
  19. e := NewEmail()
  20. e.From = "Jordan Wright <test@example.com>"
  21. e.To = []string{"test@example.com"}
  22. e.Bcc = []string{"test_bcc@example.com"}
  23. e.Cc = []string{"test_cc@example.com"}
  24. e.Subject = "Awesome Subject"
  25. return e
  26. }
  27. func basicTests(t *testing.T, e *Email) *mail.Message {
  28. raw, err := e.Bytes()
  29. if err != nil {
  30. t.Fatal("Failed to render message: ", e)
  31. }
  32. msg, err := mail.ReadMessage(bytes.NewBuffer(raw))
  33. if err != nil {
  34. t.Fatal("Could not parse rendered message: ", err)
  35. }
  36. expectedHeaders := map[string]string{
  37. "To": "test@example.com",
  38. "From": "Jordan Wright <test@example.com>",
  39. "Cc": "test_cc@example.com",
  40. "Subject": "Awesome Subject",
  41. }
  42. for header, expected := range expectedHeaders {
  43. if val := msg.Header.Get(header); val != expected {
  44. t.Errorf("Wrong value for message header %s: %v != %v", header, expected, val)
  45. }
  46. }
  47. return msg
  48. }
  49. func TestEmailText(t *testing.T) {
  50. e := prepareEmail()
  51. e.Text = []byte("Text Body is, of course, supported!\n")
  52. msg := basicTests(t, e)
  53. // Were the right headers set?
  54. ct := msg.Header.Get("Content-type")
  55. mt, _, err := mime.ParseMediaType(ct)
  56. if err != nil {
  57. t.Fatal("Content-type header is invalid: ", ct)
  58. } else if mt != "text/plain" {
  59. t.Fatalf("Content-type expected \"text/plain\", not %v", mt)
  60. }
  61. }
  62. func TestEmailWithHTMLAttachments(t *testing.T) {
  63. e := prepareEmail()
  64. // Set plain text to exercise "mime/alternative"
  65. e.Text = []byte("Text Body is, of course, supported!\n")
  66. e.HTML = []byte("<html><body>This is a text.</body></html>")
  67. // Set HTML attachment to exercise "mime/related".
  68. attachment, err := e.Attach(bytes.NewBufferString("Rad attachment"), "rad.txt", "image/png; charset=utf-8")
  69. if err != nil {
  70. t.Fatal("Could not add an attachment to the message: ", err)
  71. }
  72. attachment.HTMLRelated = true
  73. b, err := e.Bytes()
  74. if err != nil {
  75. t.Fatal("Could not serialize e-mail:", err)
  76. }
  77. // Print the bytes for ocular validation and make sure no errors.
  78. //fmt.Println(string(b))
  79. // TODO: Verify the attachments.
  80. s := trimReader{rd: bytes.NewBuffer(b)}
  81. tp := textproto.NewReader(bufio.NewReader(s))
  82. // Parse the main headers
  83. hdrs, err := tp.ReadMIMEHeader()
  84. if err != nil {
  85. t.Fatal("Could not parse the headers:", err)
  86. }
  87. // Recursively parse the MIME parts
  88. ps, err := parseMIMEParts(hdrs, tp.R)
  89. if err != nil {
  90. t.Fatal("Could not parse the MIME parts recursively:", err)
  91. }
  92. plainTextFound := false
  93. htmlFound := false
  94. imageFound := false
  95. if expected, actual := 3, len(ps); actual != expected {
  96. t.Error("Unexpected number of parts. Expected:", expected, "Was:", actual)
  97. }
  98. for _, part := range ps {
  99. // part has "header" and "body []byte"
  100. ct := part.header.Get("Content-Type")
  101. if strings.Contains(ct, "image/png") {
  102. imageFound = true
  103. }
  104. if strings.Contains(ct, "text/html") {
  105. htmlFound = true
  106. }
  107. if strings.Contains(ct, "text/plain") {
  108. plainTextFound = true
  109. }
  110. }
  111. if !plainTextFound {
  112. t.Error("Did not find plain text part.")
  113. }
  114. if !htmlFound {
  115. t.Error("Did not find HTML part.")
  116. }
  117. if !imageFound {
  118. t.Error("Did not find image part.")
  119. }
  120. }
  121. func TestEmailHTML(t *testing.T) {
  122. e := prepareEmail()
  123. e.HTML = []byte("<h1>Fancy Html is supported, too!</h1>\n")
  124. msg := basicTests(t, e)
  125. // Were the right headers set?
  126. ct := msg.Header.Get("Content-type")
  127. mt, _, err := mime.ParseMediaType(ct)
  128. if err != nil {
  129. t.Fatalf("Content-type header is invalid: %#v", ct)
  130. } else if mt != "text/html" {
  131. t.Fatalf("Content-type expected \"text/html\", not %v", mt)
  132. }
  133. }
  134. func TestEmailTextAttachment(t *testing.T) {
  135. e := prepareEmail()
  136. e.Text = []byte("Text Body is, of course, supported!\n")
  137. _, err := e.Attach(bytes.NewBufferString("Rad attachment"), "rad.txt", "text/plain; charset=utf-8")
  138. if err != nil {
  139. t.Fatal("Could not add an attachment to the message: ", err)
  140. }
  141. msg := basicTests(t, e)
  142. // Were the right headers set?
  143. ct := msg.Header.Get("Content-type")
  144. mt, params, err := mime.ParseMediaType(ct)
  145. if err != nil {
  146. t.Fatal("Content-type header is invalid: ", ct)
  147. } else if mt != "multipart/mixed" {
  148. t.Fatalf("Content-type expected \"multipart/mixed\", not %v", mt)
  149. }
  150. b := params["boundary"]
  151. if b == "" {
  152. t.Fatalf("Invalid or missing boundary parameter: %#v", b)
  153. }
  154. if len(params) != 1 {
  155. t.Fatal("Unexpected content-type parameters")
  156. }
  157. // Is the generated message parsable?
  158. mixed := multipart.NewReader(msg.Body, params["boundary"])
  159. text, err := mixed.NextPart()
  160. if err != nil {
  161. t.Fatalf("Could not find text component of email: %s", err)
  162. }
  163. // Does the text portion match what we expect?
  164. mt, _, err = mime.ParseMediaType(text.Header.Get("Content-type"))
  165. if err != nil {
  166. t.Fatal("Could not parse message's Content-Type")
  167. } else if mt != "text/plain" {
  168. t.Fatal("Message missing text/plain")
  169. }
  170. plainText, err := ioutil.ReadAll(text)
  171. if err != nil {
  172. t.Fatal("Could not read plain text component of message: ", err)
  173. }
  174. if !bytes.Equal(plainText, []byte("Text Body is, of course, supported!\r\n")) {
  175. t.Fatalf("Plain text is broken: %#q", plainText)
  176. }
  177. // Check attachments.
  178. _, err = mixed.NextPart()
  179. if err != nil {
  180. t.Fatalf("Could not find attachment component of email: %s", err)
  181. }
  182. if _, err = mixed.NextPart(); err != io.EOF {
  183. t.Error("Expected only text and one attachment!")
  184. }
  185. }
  186. func TestEmailTextHtmlAttachment(t *testing.T) {
  187. e := prepareEmail()
  188. e.Text = []byte("Text Body is, of course, supported!\n")
  189. e.HTML = []byte("<h1>Fancy Html is supported, too!</h1>\n")
  190. _, err := e.Attach(bytes.NewBufferString("Rad attachment"), "rad.txt", "text/plain; charset=utf-8")
  191. if err != nil {
  192. t.Fatal("Could not add an attachment to the message: ", err)
  193. }
  194. msg := basicTests(t, e)
  195. // Were the right headers set?
  196. ct := msg.Header.Get("Content-type")
  197. mt, params, err := mime.ParseMediaType(ct)
  198. if err != nil {
  199. t.Fatal("Content-type header is invalid: ", ct)
  200. } else if mt != "multipart/mixed" {
  201. t.Fatalf("Content-type expected \"multipart/mixed\", not %v", mt)
  202. }
  203. b := params["boundary"]
  204. if b == "" {
  205. t.Fatal("Unexpected empty boundary parameter")
  206. }
  207. if len(params) != 1 {
  208. t.Fatal("Unexpected content-type parameters")
  209. }
  210. // Is the generated message parsable?
  211. mixed := multipart.NewReader(msg.Body, params["boundary"])
  212. text, err := mixed.NextPart()
  213. if err != nil {
  214. t.Fatalf("Could not find text component of email: %s", err)
  215. }
  216. // Does the text portion match what we expect?
  217. mt, params, err = mime.ParseMediaType(text.Header.Get("Content-type"))
  218. if err != nil {
  219. t.Fatal("Could not parse message's Content-Type")
  220. } else if mt != "multipart/alternative" {
  221. t.Fatal("Message missing multipart/alternative")
  222. }
  223. mpReader := multipart.NewReader(text, params["boundary"])
  224. part, err := mpReader.NextPart()
  225. if err != nil {
  226. t.Fatal("Could not read plain text component of message: ", err)
  227. }
  228. plainText, err := ioutil.ReadAll(part)
  229. if err != nil {
  230. t.Fatal("Could not read plain text component of message: ", err)
  231. }
  232. if !bytes.Equal(plainText, []byte("Text Body is, of course, supported!\r\n")) {
  233. t.Fatalf("Plain text is broken: %#q", plainText)
  234. }
  235. // Check attachments.
  236. _, err = mixed.NextPart()
  237. if err != nil {
  238. t.Fatalf("Could not find attachment component of email: %s", err)
  239. }
  240. if _, err = mixed.NextPart(); err != io.EOF {
  241. t.Error("Expected only text and one attachment!")
  242. }
  243. }
  244. func TestEmailAttachment(t *testing.T) {
  245. e := prepareEmail()
  246. _, err := e.Attach(bytes.NewBufferString("Rad attachment"), "rad.txt", "text/plain; charset=utf-8")
  247. if err != nil {
  248. t.Fatal("Could not add an attachment to the message: ", err)
  249. }
  250. msg := basicTests(t, e)
  251. // Were the right headers set?
  252. ct := msg.Header.Get("Content-type")
  253. mt, params, err := mime.ParseMediaType(ct)
  254. if err != nil {
  255. t.Fatal("Content-type header is invalid: ", ct)
  256. } else if mt != "multipart/mixed" {
  257. t.Fatalf("Content-type expected \"multipart/mixed\", not %v", mt)
  258. }
  259. b := params["boundary"]
  260. if b == "" {
  261. t.Fatal("Unexpected empty boundary parameter")
  262. }
  263. if len(params) != 1 {
  264. t.Fatal("Unexpected content-type parameters")
  265. }
  266. // Is the generated message parsable?
  267. mixed := multipart.NewReader(msg.Body, params["boundary"])
  268. // Check attachments.
  269. _, err = mixed.NextPart()
  270. if err != nil {
  271. t.Fatalf("Could not find attachment component of email: %s", err)
  272. }
  273. if _, err = mixed.NextPart(); err != io.EOF {
  274. t.Error("Expected only one attachment!")
  275. }
  276. }
  277. func TestHeaderEncoding(t *testing.T) {
  278. cases := []struct {
  279. field string
  280. have string
  281. want string
  282. }{
  283. {
  284. field: "From",
  285. have: "Needs Encóding <encoding@example.com>, Only ASCII <foo@example.com>",
  286. want: "=?UTF-8?q?Needs_Enc=C3=B3ding?= <encoding@example.com>, Only ASCII <foo@example.com>\r\n",
  287. },
  288. {
  289. field: "To",
  290. have: "Keith Moore <moore@cs.utk.edu>, Keld Jørn Simonsen <keld@dkuug.dk>",
  291. want: "Keith Moore <moore@cs.utk.edu>, =?UTF-8?q?Keld_J=C3=B8rn_Simonsen?= <keld@dkuug.dk>\r\n",
  292. },
  293. {
  294. field: "Cc",
  295. have: "Needs Encóding <encoding@example.com>",
  296. want: "=?UTF-8?q?Needs_Enc=C3=B3ding?= <encoding@example.com>\r\n",
  297. },
  298. {
  299. field: "Subject",
  300. have: "Subject with a 🐟",
  301. want: "=?UTF-8?q?Subject_with_a_=F0=9F=90=9F?=\r\n",
  302. },
  303. {
  304. field: "Subject",
  305. have: "Subject with only ASCII",
  306. want: "Subject with only ASCII\r\n",
  307. },
  308. }
  309. buff := &bytes.Buffer{}
  310. for _, c := range cases {
  311. header := make(textproto.MIMEHeader)
  312. header.Add(c.field, c.have)
  313. buff.Reset()
  314. headerToBytes(buff, header)
  315. want := fmt.Sprintf("%s: %s", c.field, c.want)
  316. got := buff.String()
  317. if got != want {
  318. t.Errorf("invalid utf-8 header encoding. \nwant:%#v\ngot: %#v", want, got)
  319. }
  320. }
  321. }
  322. func TestEmailFromReader(t *testing.T) {
  323. ex := &Email{
  324. Subject: "Test Subject",
  325. To: []string{"Jordan Wright <jmwright798@gmail.com>"},
  326. From: "Jordan Wright <jmwright798@gmail.com>",
  327. 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"),
  328. 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"),
  329. }
  330. raw := []byte(`
  331. MIME-Version: 1.0
  332. Subject: Test Subject
  333. From: Jordan Wright <jmwright798@gmail.com>
  334. To: Jordan Wright <jmwright798@gmail.com>
  335. Content-Type: multipart/alternative; boundary=001a114fb3fc42fd6b051f834280
  336. --001a114fb3fc42fd6b051f834280
  337. Content-Type: text/plain; charset=UTF-8
  338. This is a test email with HTML Formatting. It also has very long lines so
  339. that the content must be wrapped if using quoted-printable decoding.
  340. --001a114fb3fc42fd6b051f834280
  341. Content-Type: text/html; charset=UTF-8
  342. Content-Transfer-Encoding: quoted-printable
  343. <div dir=3D"ltr">This is a test email with <b>HTML Formatting.</b>=C2=A0It =
  344. also has very long lines so that the content must be wrapped if using quote=
  345. d-printable decoding.</div>
  346. --001a114fb3fc42fd6b051f834280--`)
  347. e, err := NewEmailFromReader(bytes.NewReader(raw))
  348. if err != nil {
  349. t.Fatalf("Error creating email %s", err.Error())
  350. }
  351. if e.Subject != ex.Subject {
  352. t.Fatalf("Incorrect subject. %#q != %#q", e.Subject, ex.Subject)
  353. }
  354. if !bytes.Equal(e.Text, ex.Text) {
  355. t.Fatalf("Incorrect text: %#q != %#q", e.Text, ex.Text)
  356. }
  357. if !bytes.Equal(e.HTML, ex.HTML) {
  358. t.Fatalf("Incorrect HTML: %#q != %#q", e.HTML, ex.HTML)
  359. }
  360. if e.From != ex.From {
  361. t.Fatalf("Incorrect \"From\": %#q != %#q", e.From, ex.From)
  362. }
  363. }
  364. func TestNonAsciiEmailFromReader(t *testing.T) {
  365. ex := &Email{
  366. Subject: "Test Subject",
  367. To: []string{"Anaïs <anais@example.org>"},
  368. Cc: []string{"Patrik Fältström <paf@example.com>"},
  369. From: "Mrs Valérie Dupont <valerie.dupont@example.com>",
  370. Text: []byte("This is a test message!"),
  371. }
  372. raw := []byte(`
  373. MIME-Version: 1.0
  374. Subject: =?UTF-8?Q?Test Subject?=
  375. From: Mrs =?ISO-8859-1?Q?Val=C3=A9rie=20Dupont?= <valerie.dupont@example.com>
  376. To: =?utf-8?q?Ana=C3=AFs?= <anais@example.org>
  377. Cc: =?ISO-8859-1?Q?Patrik_F=E4ltstr=F6m?= <paf@example.com>
  378. Content-type: text/plain; charset=ISO-8859-1
  379. This is a test message!`)
  380. e, err := NewEmailFromReader(bytes.NewReader(raw))
  381. if err != nil {
  382. t.Fatalf("Error creating email %s", err.Error())
  383. }
  384. if e.Subject != ex.Subject {
  385. t.Fatalf("Incorrect subject. %#q != %#q", e.Subject, ex.Subject)
  386. }
  387. if e.From != ex.From {
  388. t.Fatalf("Incorrect \"From\": %#q != %#q", e.From, ex.From)
  389. }
  390. if e.To[0] != ex.To[0] {
  391. t.Fatalf("Incorrect \"To\": %#q != %#q", e.To, ex.To)
  392. }
  393. if e.Cc[0] != ex.Cc[0] {
  394. t.Fatalf("Incorrect \"Cc\": %#q != %#q", e.Cc, ex.Cc)
  395. }
  396. }
  397. func TestNonMultipartEmailFromReader(t *testing.T) {
  398. ex := &Email{
  399. Text: []byte("This is a test message!"),
  400. Subject: "Example Subject (no MIME Type)",
  401. Headers: textproto.MIMEHeader{},
  402. }
  403. ex.Headers.Add("Content-Type", "text/plain; charset=us-ascii")
  404. ex.Headers.Add("Message-ID", "<foobar@example.com>")
  405. raw := []byte(`From: "Foo Bar" <foobar@example.com>
  406. Content-Type: text/plain
  407. To: foobar@example.com
  408. Subject: Example Subject (no MIME Type)
  409. Message-ID: <foobar@example.com>
  410. This is a test message!`)
  411. e, err := NewEmailFromReader(bytes.NewReader(raw))
  412. if err != nil {
  413. t.Fatalf("Error creating email %s", err.Error())
  414. }
  415. if ex.Subject != e.Subject {
  416. t.Errorf("Incorrect subject. %#q != %#q\n", ex.Subject, e.Subject)
  417. }
  418. if !bytes.Equal(ex.Text, e.Text) {
  419. t.Errorf("Incorrect body. %#q != %#q\n", ex.Text, e.Text)
  420. }
  421. if ex.Headers.Get("Message-ID") != e.Headers.Get("Message-ID") {
  422. t.Errorf("Incorrect message ID. %#q != %#q\n", ex.Headers.Get("Message-ID"), e.Headers.Get("Message-ID"))
  423. }
  424. }
  425. func TestBase64EmailFromReader(t *testing.T) {
  426. ex := &Email{
  427. Subject: "Test Subject",
  428. To: []string{"Jordan Wright <jmwright798@gmail.com>"},
  429. From: "Jordan Wright <jmwright798@gmail.com>",
  430. Text: []byte("This is a test email with HTML Formatting. It also has very long lines so that the content must be wrapped if using quoted-printable decoding."),
  431. 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"),
  432. }
  433. raw := []byte(`
  434. MIME-Version: 1.0
  435. Subject: Test Subject
  436. From: Jordan Wright <jmwright798@gmail.com>
  437. To: Jordan Wright <jmwright798@gmail.com>
  438. Content-Type: multipart/alternative; boundary=001a114fb3fc42fd6b051f834280
  439. --001a114fb3fc42fd6b051f834280
  440. Content-Type: text/plain; charset=UTF-8
  441. Content-Transfer-Encoding: base64
  442. VGhpcyBpcyBhIHRlc3QgZW1haWwgd2l0aCBIVE1MIEZvcm1hdHRpbmcuIEl0IGFsc28gaGFzIHZl
  443. cnkgbG9uZyBsaW5lcyBzbyB0aGF0IHRoZSBjb250ZW50IG11c3QgYmUgd3JhcHBlZCBpZiB1c2lu
  444. ZyBxdW90ZWQtcHJpbnRhYmxlIGRlY29kaW5nLg==
  445. --001a114fb3fc42fd6b051f834280
  446. Content-Type: text/html; charset=UTF-8
  447. Content-Transfer-Encoding: quoted-printable
  448. <div dir=3D"ltr">This is a test email with <b>HTML Formatting.</b>=C2=A0It =
  449. also has very long lines so that the content must be wrapped if using quote=
  450. d-printable decoding.</div>
  451. --001a114fb3fc42fd6b051f834280--`)
  452. e, err := NewEmailFromReader(bytes.NewReader(raw))
  453. if err != nil {
  454. t.Fatalf("Error creating email %s", err.Error())
  455. }
  456. if e.Subject != ex.Subject {
  457. t.Fatalf("Incorrect subject. %#q != %#q", e.Subject, ex.Subject)
  458. }
  459. if !bytes.Equal(e.Text, ex.Text) {
  460. t.Fatalf("Incorrect text: %#q != %#q", e.Text, ex.Text)
  461. }
  462. if !bytes.Equal(e.HTML, ex.HTML) {
  463. t.Fatalf("Incorrect HTML: %#q != %#q", e.HTML, ex.HTML)
  464. }
  465. if e.From != ex.From {
  466. t.Fatalf("Incorrect \"From\": %#q != %#q", e.From, ex.From)
  467. }
  468. }
  469. func TestAttachmentEmailFromReader (t *testing.T) {
  470. ex := &Email{
  471. Subject: "Test Subject",
  472. To: []string{"Jordan Wright <jmwright798@gmail.com>"},
  473. From: "Jordan Wright <jmwright798@gmail.com>",
  474. Text: []byte("Simple text body"),
  475. HTML: []byte("<div dir=\"ltr\">Simple HTML body</div>\n"),
  476. }
  477. a, err := ex.Attach(bytes.NewReader([]byte("Let's just pretend this is raw JPEG data.")), "cat.jpeg", "image/jpeg")
  478. if err != nil {
  479. t.Fatalf("Error attaching image %s", err.Error())
  480. }
  481. raw := []byte(`
  482. From: Jordan Wright <jmwright798@gmail.com>
  483. Date: Thu, 17 Oct 2019 08:55:37 +0100
  484. Mime-Version: 1.0
  485. Content-Type: multipart/mixed;
  486. boundary=35d10c2224bd787fe700c2c6f4769ddc936eb8a0b58e9c8717e406c5abb7
  487. To: Jordan Wright <jmwright798@gmail.com>
  488. Subject: Test Subject
  489. --35d10c2224bd787fe700c2c6f4769ddc936eb8a0b58e9c8717e406c5abb7
  490. Content-Type: multipart/alternative;
  491. boundary=b10ca5b1072908cceb667e8968d3af04503b7ab07d61c9f579c15b416d7c
  492. --b10ca5b1072908cceb667e8968d3af04503b7ab07d61c9f579c15b416d7c
  493. Content-Transfer-Encoding: quoted-printable
  494. Content-Type: text/plain; charset=UTF-8
  495. Simple text body
  496. --b10ca5b1072908cceb667e8968d3af04503b7ab07d61c9f579c15b416d7c
  497. Content-Transfer-Encoding: quoted-printable
  498. Content-Type: text/html; charset=UTF-8
  499. <div dir=3D"ltr">Simple HTML body</div>
  500. --b10ca5b1072908cceb667e8968d3af04503b7ab07d61c9f579c15b416d7c--
  501. --35d10c2224bd787fe700c2c6f4769ddc936eb8a0b58e9c8717e406c5abb7
  502. Content-Disposition: attachment;
  503. filename="cat.jpeg"
  504. Content-Id: <cat.jpeg>
  505. Content-Transfer-Encoding: base64
  506. Content-Type: image/jpeg
  507. TGV0J3MganVzdCBwcmV0ZW5kIHRoaXMgaXMgcmF3IEpQRUcgZGF0YS4=
  508. --35d10c2224bd787fe700c2c6f4769ddc936eb8a0b58e9c8717e406c5abb7--`)
  509. e, err := NewEmailFromReader(bytes.NewReader(raw))
  510. if err != nil {
  511. t.Fatalf("Error creating email %s", err.Error())
  512. }
  513. if e.Subject != ex.Subject {
  514. t.Fatalf("Incorrect subject. %#q != %#q", e.Subject, ex.Subject)
  515. }
  516. if !bytes.Equal(e.Text, ex.Text) {
  517. t.Fatalf("Incorrect text: %#q != %#q", e.Text, ex.Text)
  518. }
  519. if !bytes.Equal(e.HTML, ex.HTML) {
  520. t.Fatalf("Incorrect HTML: %#q != %#q", e.HTML, ex.HTML)
  521. }
  522. if e.From != ex.From {
  523. t.Fatalf("Incorrect \"From\": %#q != %#q", e.From, ex.From)
  524. }
  525. if len(e.Attachments) != 1 {
  526. t.Fatalf("Incorrect number of attachments %d != %d", len(e.Attachments), 1)
  527. }
  528. if e.Attachments[0].Filename != a.Filename {
  529. t.Fatalf("Incorrect attachment filename %s != %s", e.Attachments[0].Filename, a.Filename)
  530. }
  531. if !bytes.Equal(e.Attachments[0].Content, a.Content) {
  532. t.Fatalf("Incorrect attachment content %#q != %#q", e.Attachments[0].Content, a.Content)
  533. }
  534. }
  535. func ExampleGmail() {
  536. e := NewEmail()
  537. e.From = "Jordan Wright <test@gmail.com>"
  538. e.To = []string{"test@example.com"}
  539. e.Bcc = []string{"test_bcc@example.com"}
  540. e.Cc = []string{"test_cc@example.com"}
  541. e.Subject = "Awesome Subject"
  542. e.Text = []byte("Text Body is, of course, supported!\n")
  543. e.HTML = []byte("<h1>Fancy Html is supported, too!</h1>\n")
  544. e.Send("smtp.gmail.com:587", smtp.PlainAuth("", e.From, "password123", "smtp.gmail.com"))
  545. }
  546. func ExampleAttach() {
  547. e := NewEmail()
  548. e.AttachFile("test.txt")
  549. }
  550. func Test_base64Wrap(t *testing.T) {
  551. file := "I'm a file long enough to force the function to wrap a\n" +
  552. "couple of lines, but I stop short of the end of one line and\n" +
  553. "have some padding dangling at the end."
  554. encoded := "SSdtIGEgZmlsZSBsb25nIGVub3VnaCB0byBmb3JjZSB0aGUgZnVuY3Rpb24gdG8gd3JhcCBhCmNv\r\n" +
  555. "dXBsZSBvZiBsaW5lcywgYnV0IEkgc3RvcCBzaG9ydCBvZiB0aGUgZW5kIG9mIG9uZSBsaW5lIGFu\r\n" +
  556. "ZApoYXZlIHNvbWUgcGFkZGluZyBkYW5nbGluZyBhdCB0aGUgZW5kLg==\r\n"
  557. var buf bytes.Buffer
  558. base64Wrap(&buf, []byte(file))
  559. if !bytes.Equal(buf.Bytes(), []byte(encoded)) {
  560. t.Fatalf("Encoded file does not match expected: %#q != %#q", string(buf.Bytes()), encoded)
  561. }
  562. }
  563. // *Since the mime library in use by ```email``` is now in the stdlib, this test is deprecated
  564. func Test_quotedPrintEncode(t *testing.T) {
  565. var buf bytes.Buffer
  566. text := []byte("Dear reader!\n\n" +
  567. "This is a test email to try and capture some of the corner cases that exist within\n" +
  568. "the quoted-printable encoding.\n" +
  569. "There are some wacky parts like =, and this input assumes UNIX line breaks so\r\n" +
  570. "it can come out a little weird. Also, we need to support unicode so here's a fish: 🐟\n")
  571. expected := []byte("Dear reader!\r\n\r\n" +
  572. "This is a test email to try and capture some of the corner cases that exist=\r\n" +
  573. " within\r\n" +
  574. "the quoted-printable encoding.\r\n" +
  575. "There are some wacky parts like =3D, and this input assumes UNIX line break=\r\n" +
  576. "s so\r\n" +
  577. "it can come out a little weird. Also, we need to support unicode so here's=\r\n" +
  578. " a fish: =F0=9F=90=9F\r\n")
  579. qp := quotedprintable.NewWriter(&buf)
  580. if _, err := qp.Write(text); err != nil {
  581. t.Fatal("quotePrintEncode: ", err)
  582. }
  583. if err := qp.Close(); err != nil {
  584. t.Fatal("Error closing writer", err)
  585. }
  586. if b := buf.Bytes(); !bytes.Equal(b, expected) {
  587. t.Errorf("quotedPrintEncode generated incorrect results: %#q != %#q", b, expected)
  588. }
  589. }
  590. func TestMultipartNoContentType(t *testing.T) {
  591. raw := []byte(`From: Mikhail Gusarov <dottedmag@dottedmag.net>
  592. To: notmuch@notmuchmail.org
  593. References: <20091117190054.GU3165@dottiness.seas.harvard.edu>
  594. Date: Wed, 18 Nov 2009 01:02:38 +0600
  595. Message-ID: <87iqd9rn3l.fsf@vertex.dottedmag>
  596. MIME-Version: 1.0
  597. Subject: Re: [notmuch] Working with Maildir storage?
  598. Content-Type: multipart/mixed; boundary="===============1958295626=="
  599. --===============1958295626==
  600. Content-Type: multipart/signed; boundary="=-=-=";
  601. micalg=pgp-sha1; protocol="application/pgp-signature"
  602. --=-=-=
  603. Content-Transfer-Encoding: quoted-printable
  604. Twas brillig at 14:00:54 17.11.2009 UTC-05 when lars@seas.harvard.edu did g=
  605. yre and gimble:
  606. --=-=-=
  607. Content-Type: application/pgp-signature
  608. -----BEGIN PGP SIGNATURE-----
  609. Version: GnuPG v1.4.9 (GNU/Linux)
  610. iQIcBAEBAgAGBQJLAvNOAAoJEJ0g9lA+M4iIjLYQAKp0PXEgl3JMOEBisH52AsIK
  611. =/ksP
  612. -----END PGP SIGNATURE-----
  613. --=-=-=--
  614. --===============1958295626==
  615. Content-Type: text/plain; charset="us-ascii"
  616. MIME-Version: 1.0
  617. Content-Transfer-Encoding: 7bit
  618. Content-Disposition: inline
  619. Testing!
  620. --===============1958295626==--
  621. `)
  622. e, err := NewEmailFromReader(bytes.NewReader(raw))
  623. if err != nil {
  624. t.Fatalf("Error when parsing email %s", err.Error())
  625. }
  626. if !bytes.Equal(e.Text, []byte("Testing!")) {
  627. t.Fatalf("Error incorrect text: %#q != %#q\n", e.Text, "Testing!")
  628. }
  629. }
  630. // *Since the mime library in use by ```email``` is now in the stdlib, this test is deprecated
  631. func Test_quotedPrintDecode(t *testing.T) {
  632. text := []byte("Dear reader!\r\n\r\n" +
  633. "This is a test email to try and capture some of the corner cases that exist=\r\n" +
  634. " within\r\n" +
  635. "the quoted-printable encoding.\r\n" +
  636. "There are some wacky parts like =3D, and this input assumes UNIX line break=\r\n" +
  637. "s so\r\n" +
  638. "it can come out a little weird. Also, we need to support unicode so here's=\r\n" +
  639. " a fish: =F0=9F=90=9F\r\n")
  640. expected := []byte("Dear reader!\r\n\r\n" +
  641. "This is a test email to try and capture some of the corner cases that exist within\r\n" +
  642. "the quoted-printable encoding.\r\n" +
  643. "There are some wacky parts like =, and this input assumes UNIX line breaks so\r\n" +
  644. "it can come out a little weird. Also, we need to support unicode so here's a fish: 🐟\r\n")
  645. qp := quotedprintable.NewReader(bytes.NewReader(text))
  646. got, err := ioutil.ReadAll(qp)
  647. if err != nil {
  648. t.Fatal("quotePrintDecode: ", err)
  649. }
  650. if !bytes.Equal(got, expected) {
  651. t.Errorf("quotedPrintDecode generated incorrect results: %#q != %#q", got, expected)
  652. }
  653. }
  654. func Benchmark_base64Wrap(b *testing.B) {
  655. // Reasonable base case; 128K random bytes
  656. file := make([]byte, 128*1024)
  657. if _, err := rand.Read(file); err != nil {
  658. panic(err)
  659. }
  660. for i := 0; i <= b.N; i++ {
  661. base64Wrap(ioutil.Discard, file)
  662. }
  663. }
  664. func TestParseSender(t *testing.T) {
  665. var cases = []struct {
  666. e Email
  667. want string
  668. haserr bool
  669. }{
  670. {
  671. Email{From: "from@test.com"},
  672. "from@test.com",
  673. false,
  674. },
  675. {
  676. Email{Sender: "sender@test.com", From: "from@test.com"},
  677. "sender@test.com",
  678. false,
  679. },
  680. {
  681. Email{Sender: "bad_address_sender"},
  682. "",
  683. true,
  684. },
  685. {
  686. Email{Sender: "good@sender.com", From: "bad_address_from"},
  687. "good@sender.com",
  688. false,
  689. },
  690. }
  691. for i, testcase := range cases {
  692. got, err := testcase.e.parseSender()
  693. if got != testcase.want || (err != nil) != testcase.haserr {
  694. t.Errorf(`%d: got %s != want %s or error "%t" != "%t"`, i+1, got, testcase.want, err != nil, testcase.haserr)
  695. }
  696. }
  697. }