email_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  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>", "also@example.com"},
  326. From: "Jordan Wright <jmwright798@gmail.com>",
  327. Cc: []string{"one@example.com", "Two <two@example.com>"},
  328. Bcc: []string{"three@example.com", "Four <four@example.com>"},
  329. 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"),
  330. 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"),
  331. }
  332. raw := []byte(`
  333. MIME-Version: 1.0
  334. Subject: Test Subject
  335. From: Jordan Wright <jmwright798@gmail.com>
  336. To: Jordan Wright <jmwright798@gmail.com>, also@example.com
  337. Cc: one@example.com, Two <two@example.com>
  338. Bcc: three@example.com, Four <four@example.com>
  339. Content-Type: multipart/alternative; boundary=001a114fb3fc42fd6b051f834280
  340. --001a114fb3fc42fd6b051f834280
  341. Content-Type: text/plain; charset=UTF-8
  342. This is a test email with HTML Formatting. It also has very long lines so
  343. that the content must be wrapped if using quoted-printable decoding.
  344. --001a114fb3fc42fd6b051f834280
  345. Content-Type: text/html; charset=UTF-8
  346. Content-Transfer-Encoding: quoted-printable
  347. <div dir=3D"ltr">This is a test email with <b>HTML Formatting.</b>=C2=A0It =
  348. also has very long lines so that the content must be wrapped if using quote=
  349. d-printable decoding.</div>
  350. --001a114fb3fc42fd6b051f834280--`)
  351. e, err := NewEmailFromReader(bytes.NewReader(raw))
  352. if err != nil {
  353. t.Fatalf("Error creating email %s", err.Error())
  354. }
  355. if e.Subject != ex.Subject {
  356. t.Fatalf("Incorrect subject. %#q != %#q", e.Subject, ex.Subject)
  357. }
  358. if !bytes.Equal(e.Text, ex.Text) {
  359. t.Fatalf("Incorrect text: %#q != %#q", e.Text, ex.Text)
  360. }
  361. if !bytes.Equal(e.HTML, ex.HTML) {
  362. t.Fatalf("Incorrect HTML: %#q != %#q", e.HTML, ex.HTML)
  363. }
  364. if e.From != ex.From {
  365. t.Fatalf("Incorrect \"From\": %#q != %#q", e.From, ex.From)
  366. }
  367. if len(e.To) != len(ex.To) {
  368. t.Fatalf("Incorrect number of \"To\" addresses: %v != %v", len(e.To), len(ex.To))
  369. }
  370. if e.To[0] != ex.To[0] {
  371. t.Fatalf("Incorrect \"To[0]\": %#q != %#q", e.To[0], ex.To[0])
  372. }
  373. if e.To[1] != ex.To[1] {
  374. t.Fatalf("Incorrect \"To[1]\": %#q != %#q", e.To[1], ex.To[1])
  375. }
  376. if len(e.Cc) != len(ex.Cc) {
  377. t.Fatalf("Incorrect number of \"Cc\" addresses: %v != %v", len(e.Cc), len(ex.Cc))
  378. }
  379. if e.Cc[0] != ex.Cc[0] {
  380. t.Fatalf("Incorrect \"Cc[0]\": %#q != %#q", e.Cc[0], ex.Cc[0])
  381. }
  382. if e.Cc[1] != ex.Cc[1] {
  383. t.Fatalf("Incorrect \"Cc[1]\": %#q != %#q", e.Cc[1], ex.Cc[1])
  384. }
  385. if len(e.Bcc) != len(ex.Bcc) {
  386. t.Fatalf("Incorrect number of \"Bcc\" addresses: %v != %v", len(e.Bcc), len(ex.Bcc))
  387. }
  388. if e.Bcc[0] != ex.Bcc[0] {
  389. t.Fatalf("Incorrect \"Bcc[0]\": %#q != %#q", e.Cc[0], ex.Cc[0])
  390. }
  391. if e.Bcc[1] != ex.Bcc[1] {
  392. t.Fatalf("Incorrect \"Bcc[1]\": %#q != %#q", e.Bcc[1], ex.Bcc[1])
  393. }
  394. }
  395. func TestNonAsciiEmailFromReader(t *testing.T) {
  396. ex := &Email{
  397. Subject: "Test Subject",
  398. To: []string{"Anaïs <anais@example.org>"},
  399. Cc: []string{"Patrik Fältström <paf@example.com>"},
  400. From: "Mrs Valérie Dupont <valerie.dupont@example.com>",
  401. Text: []byte("This is a test message!"),
  402. }
  403. raw := []byte(`
  404. MIME-Version: 1.0
  405. Subject: =?UTF-8?Q?Test Subject?=
  406. From: Mrs =?ISO-8859-1?Q?Val=C3=A9rie=20Dupont?= <valerie.dupont@example.com>
  407. To: =?utf-8?q?Ana=C3=AFs?= <anais@example.org>
  408. Cc: =?ISO-8859-1?Q?Patrik_F=E4ltstr=F6m?= <paf@example.com>
  409. Content-type: text/plain; charset=ISO-8859-1
  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 e.Subject != ex.Subject {
  416. t.Fatalf("Incorrect subject. %#q != %#q", e.Subject, ex.Subject)
  417. }
  418. if e.From != ex.From {
  419. t.Fatalf("Incorrect \"From\": %#q != %#q", e.From, ex.From)
  420. }
  421. if e.To[0] != ex.To[0] {
  422. t.Fatalf("Incorrect \"To\": %#q != %#q", e.To, ex.To)
  423. }
  424. if e.Cc[0] != ex.Cc[0] {
  425. t.Fatalf("Incorrect \"Cc\": %#q != %#q", e.Cc, ex.Cc)
  426. }
  427. }
  428. func TestNonMultipartEmailFromReader(t *testing.T) {
  429. ex := &Email{
  430. Text: []byte("This is a test message!"),
  431. Subject: "Example Subject (no MIME Type)",
  432. Headers: textproto.MIMEHeader{},
  433. }
  434. ex.Headers.Add("Content-Type", "text/plain; charset=us-ascii")
  435. ex.Headers.Add("Message-ID", "<foobar@example.com>")
  436. raw := []byte(`From: "Foo Bar" <foobar@example.com>
  437. Content-Type: text/plain
  438. To: foobar@example.com
  439. Subject: Example Subject (no MIME Type)
  440. Message-ID: <foobar@example.com>
  441. This is a test message!`)
  442. e, err := NewEmailFromReader(bytes.NewReader(raw))
  443. if err != nil {
  444. t.Fatalf("Error creating email %s", err.Error())
  445. }
  446. if ex.Subject != e.Subject {
  447. t.Errorf("Incorrect subject. %#q != %#q\n", ex.Subject, e.Subject)
  448. }
  449. if !bytes.Equal(ex.Text, e.Text) {
  450. t.Errorf("Incorrect body. %#q != %#q\n", ex.Text, e.Text)
  451. }
  452. if ex.Headers.Get("Message-ID") != e.Headers.Get("Message-ID") {
  453. t.Errorf("Incorrect message ID. %#q != %#q\n", ex.Headers.Get("Message-ID"), e.Headers.Get("Message-ID"))
  454. }
  455. }
  456. func TestBase64EmailFromReader(t *testing.T) {
  457. ex := &Email{
  458. Subject: "Test Subject",
  459. To: []string{"Jordan Wright <jmwright798@gmail.com>"},
  460. From: "Jordan Wright <jmwright798@gmail.com>",
  461. 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."),
  462. 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"),
  463. }
  464. raw := []byte(`
  465. MIME-Version: 1.0
  466. Subject: Test Subject
  467. From: Jordan Wright <jmwright798@gmail.com>
  468. To: Jordan Wright <jmwright798@gmail.com>
  469. Content-Type: multipart/alternative; boundary=001a114fb3fc42fd6b051f834280
  470. --001a114fb3fc42fd6b051f834280
  471. Content-Type: text/plain; charset=UTF-8
  472. Content-Transfer-Encoding: base64
  473. VGhpcyBpcyBhIHRlc3QgZW1haWwgd2l0aCBIVE1MIEZvcm1hdHRpbmcuIEl0IGFsc28gaGFzIHZl
  474. cnkgbG9uZyBsaW5lcyBzbyB0aGF0IHRoZSBjb250ZW50IG11c3QgYmUgd3JhcHBlZCBpZiB1c2lu
  475. ZyBxdW90ZWQtcHJpbnRhYmxlIGRlY29kaW5nLg==
  476. --001a114fb3fc42fd6b051f834280
  477. Content-Type: text/html; charset=UTF-8
  478. Content-Transfer-Encoding: quoted-printable
  479. <div dir=3D"ltr">This is a test email with <b>HTML Formatting.</b>=C2=A0It =
  480. also has very long lines so that the content must be wrapped if using quote=
  481. d-printable decoding.</div>
  482. --001a114fb3fc42fd6b051f834280--`)
  483. e, err := NewEmailFromReader(bytes.NewReader(raw))
  484. if err != nil {
  485. t.Fatalf("Error creating email %s", err.Error())
  486. }
  487. if e.Subject != ex.Subject {
  488. t.Fatalf("Incorrect subject. %#q != %#q", e.Subject, ex.Subject)
  489. }
  490. if !bytes.Equal(e.Text, ex.Text) {
  491. t.Fatalf("Incorrect text: %#q != %#q", e.Text, ex.Text)
  492. }
  493. if !bytes.Equal(e.HTML, ex.HTML) {
  494. t.Fatalf("Incorrect HTML: %#q != %#q", e.HTML, ex.HTML)
  495. }
  496. if e.From != ex.From {
  497. t.Fatalf("Incorrect \"From\": %#q != %#q", e.From, ex.From)
  498. }
  499. }
  500. func TestAttachmentEmailFromReader(t *testing.T) {
  501. ex := &Email{
  502. Subject: "Test Subject",
  503. To: []string{"Jordan Wright <jmwright798@gmail.com>"},
  504. From: "Jordan Wright <jmwright798@gmail.com>",
  505. Text: []byte("Simple text body"),
  506. HTML: []byte("<div dir=\"ltr\">Simple HTML body</div>\n"),
  507. }
  508. a, err := ex.Attach(bytes.NewReader([]byte("Let's just pretend this is raw JPEG data.")), "cat.jpeg", "image/jpeg")
  509. if err != nil {
  510. t.Fatalf("Error attaching image %s", err.Error())
  511. }
  512. b, err := ex.Attach(bytes.NewReader([]byte("Let's just pretend this is raw JPEG data.")), "cat-inline.jpeg", "image/jpeg")
  513. if err != nil {
  514. t.Fatalf("Error attaching inline image %s", err.Error())
  515. }
  516. raw := []byte(`
  517. From: Jordan Wright <jmwright798@gmail.com>
  518. Date: Thu, 17 Oct 2019 08:55:37 +0100
  519. Mime-Version: 1.0
  520. Content-Type: multipart/mixed;
  521. boundary=35d10c2224bd787fe700c2c6f4769ddc936eb8a0b58e9c8717e406c5abb7
  522. To: Jordan Wright <jmwright798@gmail.com>
  523. Subject: Test Subject
  524. --35d10c2224bd787fe700c2c6f4769ddc936eb8a0b58e9c8717e406c5abb7
  525. Content-Type: multipart/alternative;
  526. boundary=b10ca5b1072908cceb667e8968d3af04503b7ab07d61c9f579c15b416d7c
  527. --b10ca5b1072908cceb667e8968d3af04503b7ab07d61c9f579c15b416d7c
  528. Content-Transfer-Encoding: quoted-printable
  529. Content-Type: text/plain; charset=UTF-8
  530. Simple text body
  531. --b10ca5b1072908cceb667e8968d3af04503b7ab07d61c9f579c15b416d7c
  532. Content-Transfer-Encoding: quoted-printable
  533. Content-Type: text/html; charset=UTF-8
  534. <div dir=3D"ltr">Simple HTML body</div>
  535. --b10ca5b1072908cceb667e8968d3af04503b7ab07d61c9f579c15b416d7c--
  536. --35d10c2224bd787fe700c2c6f4769ddc936eb8a0b58e9c8717e406c5abb7
  537. Content-Disposition: attachment;
  538. filename="cat.jpeg"
  539. Content-Id: <cat.jpeg>
  540. Content-Transfer-Encoding: base64
  541. Content-Type: image/jpeg
  542. TGV0J3MganVzdCBwcmV0ZW5kIHRoaXMgaXMgcmF3IEpQRUcgZGF0YS4=
  543. --35d10c2224bd787fe700c2c6f4769ddc936eb8a0b58e9c8717e406c5abb7
  544. Content-Disposition: inline;
  545. filename="cat-inline.jpeg"
  546. Content-Id: <cat-inline.jpeg>
  547. Content-Transfer-Encoding: base64
  548. Content-Type: image/jpeg
  549. TGV0J3MganVzdCBwcmV0ZW5kIHRoaXMgaXMgcmF3IEpQRUcgZGF0YS4=
  550. --35d10c2224bd787fe700c2c6f4769ddc936eb8a0b58e9c8717e406c5abb7--`)
  551. e, err := NewEmailFromReader(bytes.NewReader(raw))
  552. if err != nil {
  553. t.Fatalf("Error creating email %s", err.Error())
  554. }
  555. if e.Subject != ex.Subject {
  556. t.Fatalf("Incorrect subject. %#q != %#q", e.Subject, ex.Subject)
  557. }
  558. if !bytes.Equal(e.Text, ex.Text) {
  559. t.Fatalf("Incorrect text: %#q != %#q", e.Text, ex.Text)
  560. }
  561. if !bytes.Equal(e.HTML, ex.HTML) {
  562. t.Fatalf("Incorrect HTML: %#q != %#q", e.HTML, ex.HTML)
  563. }
  564. if e.From != ex.From {
  565. t.Fatalf("Incorrect \"From\": %#q != %#q", e.From, ex.From)
  566. }
  567. if len(e.Attachments) != 2 {
  568. t.Fatalf("Incorrect number of attachments %d != %d", len(e.Attachments), 1)
  569. }
  570. if e.Attachments[0].Filename != a.Filename {
  571. t.Fatalf("Incorrect attachment filename %s != %s", e.Attachments[0].Filename, a.Filename)
  572. }
  573. if !bytes.Equal(e.Attachments[0].Content, a.Content) {
  574. t.Fatalf("Incorrect attachment content %#q != %#q", e.Attachments[0].Content, a.Content)
  575. }
  576. if e.Attachments[1].Filename != b.Filename {
  577. t.Fatalf("Incorrect attachment filename %s != %s", e.Attachments[1].Filename, b.Filename)
  578. }
  579. if !bytes.Equal(e.Attachments[1].Content, b.Content) {
  580. t.Fatalf("Incorrect attachment content %#q != %#q", e.Attachments[1].Content, b.Content)
  581. }
  582. }
  583. func ExampleGmail() {
  584. e := NewEmail()
  585. e.From = "Jordan Wright <test@gmail.com>"
  586. e.To = []string{"test@example.com"}
  587. e.Bcc = []string{"test_bcc@example.com"}
  588. e.Cc = []string{"test_cc@example.com"}
  589. e.Subject = "Awesome Subject"
  590. e.Text = []byte("Text Body is, of course, supported!\n")
  591. e.HTML = []byte("<h1>Fancy Html is supported, too!</h1>\n")
  592. e.Send("smtp.gmail.com:587", smtp.PlainAuth("", e.From, "password123", "smtp.gmail.com"))
  593. }
  594. func ExampleAttach() {
  595. e := NewEmail()
  596. e.AttachFile("test.txt")
  597. }
  598. func Test_base64Wrap(t *testing.T) {
  599. file := "I'm a file long enough to force the function to wrap a\n" +
  600. "couple of lines, but I stop short of the end of one line and\n" +
  601. "have some padding dangling at the end."
  602. encoded := "SSdtIGEgZmlsZSBsb25nIGVub3VnaCB0byBmb3JjZSB0aGUgZnVuY3Rpb24gdG8gd3JhcCBhCmNv\r\n" +
  603. "dXBsZSBvZiBsaW5lcywgYnV0IEkgc3RvcCBzaG9ydCBvZiB0aGUgZW5kIG9mIG9uZSBsaW5lIGFu\r\n" +
  604. "ZApoYXZlIHNvbWUgcGFkZGluZyBkYW5nbGluZyBhdCB0aGUgZW5kLg==\r\n"
  605. var buf bytes.Buffer
  606. base64Wrap(&buf, []byte(file))
  607. if !bytes.Equal(buf.Bytes(), []byte(encoded)) {
  608. t.Fatalf("Encoded file does not match expected: %#q != %#q", string(buf.Bytes()), encoded)
  609. }
  610. }
  611. // *Since the mime library in use by ```email``` is now in the stdlib, this test is deprecated
  612. func Test_quotedPrintEncode(t *testing.T) {
  613. var buf bytes.Buffer
  614. text := []byte("Dear reader!\n\n" +
  615. "This is a test email to try and capture some of the corner cases that exist within\n" +
  616. "the quoted-printable encoding.\n" +
  617. "There are some wacky parts like =, and this input assumes UNIX line breaks so\r\n" +
  618. "it can come out a little weird. Also, we need to support unicode so here's a fish: 🐟\n")
  619. expected := []byte("Dear reader!\r\n\r\n" +
  620. "This is a test email to try and capture some of the corner cases that exist=\r\n" +
  621. " within\r\n" +
  622. "the quoted-printable encoding.\r\n" +
  623. "There are some wacky parts like =3D, and this input assumes UNIX line break=\r\n" +
  624. "s so\r\n" +
  625. "it can come out a little weird. Also, we need to support unicode so here's=\r\n" +
  626. " a fish: =F0=9F=90=9F\r\n")
  627. qp := quotedprintable.NewWriter(&buf)
  628. if _, err := qp.Write(text); err != nil {
  629. t.Fatal("quotePrintEncode: ", err)
  630. }
  631. if err := qp.Close(); err != nil {
  632. t.Fatal("Error closing writer", err)
  633. }
  634. if b := buf.Bytes(); !bytes.Equal(b, expected) {
  635. t.Errorf("quotedPrintEncode generated incorrect results: %#q != %#q", b, expected)
  636. }
  637. }
  638. func TestMultipartNoContentType(t *testing.T) {
  639. raw := []byte(`From: Mikhail Gusarov <dottedmag@dottedmag.net>
  640. To: notmuch@notmuchmail.org
  641. References: <20091117190054.GU3165@dottiness.seas.harvard.edu>
  642. Date: Wed, 18 Nov 2009 01:02:38 +0600
  643. Message-ID: <87iqd9rn3l.fsf@vertex.dottedmag>
  644. MIME-Version: 1.0
  645. Subject: Re: [notmuch] Working with Maildir storage?
  646. Content-Type: multipart/mixed; boundary="===============1958295626=="
  647. --===============1958295626==
  648. Content-Type: multipart/signed; boundary="=-=-=";
  649. micalg=pgp-sha1; protocol="application/pgp-signature"
  650. --=-=-=
  651. Content-Transfer-Encoding: quoted-printable
  652. Twas brillig at 14:00:54 17.11.2009 UTC-05 when lars@seas.harvard.edu did g=
  653. yre and gimble:
  654. --=-=-=
  655. Content-Type: application/pgp-signature
  656. -----BEGIN PGP SIGNATURE-----
  657. Version: GnuPG v1.4.9 (GNU/Linux)
  658. iQIcBAEBAgAGBQJLAvNOAAoJEJ0g9lA+M4iIjLYQAKp0PXEgl3JMOEBisH52AsIK
  659. =/ksP
  660. -----END PGP SIGNATURE-----
  661. --=-=-=--
  662. --===============1958295626==
  663. Content-Type: text/plain; charset="us-ascii"
  664. MIME-Version: 1.0
  665. Content-Transfer-Encoding: 7bit
  666. Content-Disposition: inline
  667. Testing!
  668. --===============1958295626==--
  669. `)
  670. e, err := NewEmailFromReader(bytes.NewReader(raw))
  671. if err != nil {
  672. t.Fatalf("Error when parsing email %s", err.Error())
  673. }
  674. if !bytes.Equal(e.Text, []byte("Testing!")) {
  675. t.Fatalf("Error incorrect text: %#q != %#q\n", e.Text, "Testing!")
  676. }
  677. }
  678. // *Since the mime library in use by ```email``` is now in the stdlib, this test is deprecated
  679. func Test_quotedPrintDecode(t *testing.T) {
  680. text := []byte("Dear reader!\r\n\r\n" +
  681. "This is a test email to try and capture some of the corner cases that exist=\r\n" +
  682. " within\r\n" +
  683. "the quoted-printable encoding.\r\n" +
  684. "There are some wacky parts like =3D, and this input assumes UNIX line break=\r\n" +
  685. "s so\r\n" +
  686. "it can come out a little weird. Also, we need to support unicode so here's=\r\n" +
  687. " a fish: =F0=9F=90=9F\r\n")
  688. expected := []byte("Dear reader!\r\n\r\n" +
  689. "This is a test email to try and capture some of the corner cases that exist within\r\n" +
  690. "the quoted-printable encoding.\r\n" +
  691. "There are some wacky parts like =, and this input assumes UNIX line breaks so\r\n" +
  692. "it can come out a little weird. Also, we need to support unicode so here's a fish: 🐟\r\n")
  693. qp := quotedprintable.NewReader(bytes.NewReader(text))
  694. got, err := ioutil.ReadAll(qp)
  695. if err != nil {
  696. t.Fatal("quotePrintDecode: ", err)
  697. }
  698. if !bytes.Equal(got, expected) {
  699. t.Errorf("quotedPrintDecode generated incorrect results: %#q != %#q", got, expected)
  700. }
  701. }
  702. func Benchmark_base64Wrap(b *testing.B) {
  703. // Reasonable base case; 128K random bytes
  704. file := make([]byte, 128*1024)
  705. if _, err := rand.Read(file); err != nil {
  706. panic(err)
  707. }
  708. for i := 0; i <= b.N; i++ {
  709. base64Wrap(ioutil.Discard, file)
  710. }
  711. }
  712. func TestParseSender(t *testing.T) {
  713. var cases = []struct {
  714. e Email
  715. want string
  716. haserr bool
  717. }{
  718. {
  719. Email{From: "from@test.com"},
  720. "from@test.com",
  721. false,
  722. },
  723. {
  724. Email{Sender: "sender@test.com", From: "from@test.com"},
  725. "sender@test.com",
  726. false,
  727. },
  728. {
  729. Email{Sender: "bad_address_sender"},
  730. "",
  731. true,
  732. },
  733. {
  734. Email{Sender: "good@sender.com", From: "bad_address_from"},
  735. "good@sender.com",
  736. false,
  737. },
  738. }
  739. for i, testcase := range cases {
  740. got, err := testcase.e.parseSender()
  741. if got != testcase.want || (err != nil) != testcase.haserr {
  742. t.Errorf(`%d: got %s != want %s or error "%t" != "%t"`, i+1, got, testcase.want, err != nil, testcase.haserr)
  743. }
  744. }
  745. }