email_test.go 28 KB

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