/
test_template_message.py
989 lines (805 loc) 路 31.3 KB
/
test_template_message.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
# coding=utf-8
# Python 2 source containing unicode https://www.python.org/dev/peps/pep-0263/
"""
Tests for TemplateMessage.
Andrew DeOrio <awdeorio@umich.edu>
"""
import os
import re
import shutil
import textwrap
import collections
import jinja2
import pytest
import markdown
from mailmerge.template_message import TemplateMessage
from mailmerge.utils import MailmergeError
from . import utils
# Python 2 pathlib support requires backport
try:
from pathlib2 import Path
except ImportError:
from pathlib import Path
def test_simple(tmp_path):
"""Render a simple template."""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
SUBJECT: Testing mailmerge
FROM: from@test.com
Hello {{name}}!
"""))
template_message = TemplateMessage(template_path)
sender, recipients, message = template_message.render({
"name": "world",
})
assert sender == "from@test.com"
assert recipients == ["to@test.com"]
plaintext = message.get_payload()
assert "Hello world!" in plaintext
def test_no_substitutions(tmp_path):
"""Render a template with an empty context."""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
SUBJECT: Testing mailmerge
FROM: from@test.com
Hello world!
"""))
template_message = TemplateMessage(template_path)
sender, recipients, message = template_message.render({})
assert sender == "from@test.com"
assert recipients == ["to@test.com"]
plaintext = message.get_payload()
assert "Hello world!" in plaintext
def test_multiple_substitutions(tmp_path):
"""Render a template with multiple context variables."""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: {{email}}
FROM: from@test.com
Hi, {{name}},
Your number is {{number}}.
"""))
template_message = TemplateMessage(template_path)
sender, recipients, message = template_message.render({
"email": "myself@mydomain.com",
"name": "Myself",
"number": 17,
})
assert sender == "from@test.com"
assert recipients == ["myself@mydomain.com"]
plaintext = message.get_payload()
assert "Hi, Myself," in plaintext
assert "Your number is 17" in plaintext
def test_bad_jinja(tmp_path):
"""Bad jinja template should produce an error."""
template_path = tmp_path / "template.txt"
template_path.write_text(u"TO: {{error_not_in_database}}")
template_message = TemplateMessage(template_path)
with pytest.raises(jinja2.exceptions.UndefinedError):
template_message.render({"name": "Bob", "number": 17})
def test_cc_bcc(tmp_path):
"""CC recipients should receive a copy."""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: {{email}}
SUBJECT: Testing mailmerge
FROM: My Self <myself@mydomain.com>
CC: My Colleague <mycolleague@mydomain.com>
BCC: Secret <secret@mydomain.com>
Hello world
"""))
template_message = TemplateMessage(template_path)
sender, recipients, message = template_message.render({
"email": "myself@mydomain.com",
})
# Verify recipients include CC and BCC
assert sender == "My Self <myself@mydomain.com>"
assert recipients == [
"myself@mydomain.com",
"mycolleague@mydomain.com",
"secret@mydomain.com",
]
# Make sure BCC recipients are *not* in the message
plaintext = message.get_payload()
assert "BCC" not in plaintext
assert "secret@mydomain.com" not in plaintext
assert "Secret" not in plaintext
def test_html(tmp_path):
"""Verify HTML template results in a simple rendered message."""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
SUBJECT: Testing mailmerge
FROM: from@test.com
Content-Type: text/html
<html>
<body>
<p>{{message}}</p>
</body>
</html>
"""))
template_message = TemplateMessage(template_path)
sender, recipients, message = template_message.render({
"message": "Hello world"
})
# Verify sender and recipients
assert sender == "from@test.com"
assert recipients == ["to@test.com"]
# A simple HTML message is not multipart
assert not message.is_multipart()
# Verify encoding
assert message.get_charset() == "us-ascii"
assert message.get_content_charset() == "us-ascii"
assert message.get_content_type() == "text/html"
# Verify content
htmltext = message.get_payload()
htmltext = re.sub(r"\s+", "", htmltext) # Strip whitespace
assert htmltext == "<html><body><p>Helloworld</p></body></html>"
def test_html_plaintext(tmp_path):
"""Verify HTML and plaintest multipart template."""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
SUBJECT: Testing mailmerge
FROM: from@test.com
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="boundary"
This is a MIME-encoded message. If you are seeing this, your mail
reader is old.
--boundary
Content-Type: text/plain; charset=us-ascii
{{message}}
--boundary
Content-Type: text/html; charset=us-ascii
<html>
<body>
<p>{{message}}</p>
</body>
</html>
"""))
template_message = TemplateMessage(template_path)
sender, recipients, message = template_message.render({
"message": "Hello world"
})
# Verify sender and recipients
assert sender == "from@test.com"
assert recipients == ["to@test.com"]
# Should be multipart: plaintext and HTML
assert message.is_multipart()
parts = message.get_payload()
assert len(parts) == 2
plaintext_part, html_part = parts
# Verify plaintext part
assert plaintext_part.get_charset() == "us-ascii"
assert plaintext_part.get_content_charset() == "us-ascii"
assert plaintext_part.get_content_type() == "text/plain"
plaintext = plaintext_part.get_payload()
plaintext = plaintext.strip()
assert plaintext == "Hello world"
# Verify html part
assert html_part.get_charset() == "us-ascii"
assert html_part.get_content_charset() == "us-ascii"
assert html_part.get_content_type() == "text/html"
htmltext = html_part.get_payload()
htmltext = re.sub(r"\s+", "", htmltext) # Strip whitespace
assert htmltext == "<html><body><p>Helloworld</p></body></html>"
def test_markdown(tmp_path):
"""Markdown messages should be converted to HTML."""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: {{email}}
SUBJECT: Testing mailmerge
FROM: Bob <bob@bobdomain.com>
CONTENT-TYPE: text/markdown
Hi, **{{name}}**,
You can add:
- Emphasis, aka italics, with *asterisks* or _underscores_.
- Strong emphasis, aka bold, with **asterisks** or __underscores__.
- Combined emphasis with **asterisks and _underscores_**.
- Strikethrough uses two tildes. ~~Scratch this.~~
- Unordered lists like this one.
- Ordered lists with numbers:
1. Item 1
2. Item 2
- Preformatted text with `backticks`.
---
# This is a heading.
## And another heading.
How about some [hyperlinks](http://bit.ly/eecs485-wn19-p6)?
Or code blocks?
```
print("Hello world.")
```
Here's an image not attached with the email:
![python logo not attached](
http://pluspng.com/img-png/python-logo-png-open-2000.png)
"""))
template_message = TemplateMessage(template_path)
sender, recipients, message = template_message.render({
"email": "myself@mydomain.com",
"name": "Myself",
"number": 17,
})
# Verify sender and recipients
assert sender == "Bob <bob@bobdomain.com>"
assert recipients == ["myself@mydomain.com"]
# Verify message is multipart
assert message.is_multipart()
# Make sure there is a plaintext part and an HTML part
payload = message.get_payload()
assert len(payload) == 2
# Ensure that the first part is plaintext and the last part
# is HTML (as per RFC 2046)
plaintext_part = payload[0]
assert plaintext_part['Content-Type'].startswith("text/plain")
plaintext_encoding = str(plaintext_part.get_charset())
plaintext = plaintext_part.get_payload(decode=True) \
.decode(plaintext_encoding)
html_part = payload[1]
assert html_part['Content-Type'].startswith("text/html")
html_encoding = str(html_part.get_charset())
htmltext = html_part.get_payload(decode=True) \
.decode(html_encoding)
# Verify rendered Markdown
rendered = markdown.markdown(plaintext)
htmltext_correct = "<html><body>{}</body></html>".format(rendered)
assert htmltext.strip() == htmltext_correct.strip()
def test_markdown_encoding(tmp_path):
"""Verify encoding is preserved when rendering a Markdown template.
See Issue #59 for a detailed explanation
https://github.com/awdeorio/mailmerge/issues/59
"""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: {{email}}
SUBJECT: Testing mailmerge
FROM: test@example.com
CONTENT-TYPE: text/markdown
Hi, {{name}},
忙酶氓
"""))
template_message = TemplateMessage(template_path)
_, _, message = template_message.render({
"email": "myself@mydomain.com",
"name": "Myself",
})
# Message should contain an unrendered Markdown plaintext part and a
# rendered Markdown HTML part
plaintext_part, html_part = message.get_payload()
# Verify encodings
assert str(plaintext_part.get_charset()) == "utf-8"
assert str(html_part.get_charset()) == "utf-8"
assert plaintext_part["Content-Transfer-Encoding"] == "base64"
assert html_part["Content-Transfer-Encoding"] == "base64"
# Verify content, which is base64 encoded
plaintext = plaintext_part.get_payload(decode=True).decode("utf-8")
htmltext = html_part.get_payload(decode=True).decode("utf-8")
assert plaintext == u"Hi, Myself,\n忙酶氓"
assert htmltext == u"<html><body><p>Hi, Myself,\n忙酶氓</p></body></html>"
Attachment = collections.namedtuple(
"Attachment",
["filename", "content"],
)
def extract_attachments(message):
"""Return a list of attachments as (filename, content) named tuples."""
attachments = []
for part in message.walk():
if part.get_content_maintype() == "multipart":
continue
if part.get_content_maintype() == "text":
continue
if part.get("Content-Disposition") == "inline":
continue
if part.get("Content-Disposition") is None:
continue
if part['content-type'].startswith('application/octet-stream'):
attachments.append(Attachment(
filename=part.get_param('name'),
content=part.get_payload(decode=True),
))
return attachments
def test_attachment_simple(tmpdir):
"""Verify a simple attachment."""
# Simple attachment
attachment_path = Path(tmpdir/"attachment.txt")
attachment_path.write_text(u"Hello world\n")
# Simple template
template_path = Path(tmpdir/"template.txt")
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
FROM: from@test.com
ATTACHMENT: attachment.txt
Hello world
"""))
# Render in tmpdir
with tmpdir.as_cwd():
template_message = TemplateMessage(template_path)
sender, recipients, message = template_message.render({})
# Verify sender and recipients
assert sender == "from@test.com"
assert recipients == ["to@test.com"]
# Verify message is multipart and contains attachment
assert message.is_multipart()
attachments = extract_attachments(message)
assert len(attachments) == 1
# Verify attachment
filename, content = attachments[0]
assert filename == "attachment.txt"
assert content == b"Hello world\n"
def test_attachment_relative(tmpdir):
"""Attachment with a relative file path is relative to template dir."""
# Simple attachment
attachment_path = Path(tmpdir/"attachment.txt")
attachment_path.write_text(u"Hello world\n")
# Simple template
template_path = Path(tmpdir/"template.txt")
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
FROM: from@test.com
ATTACHMENT: attachment.txt
Hello world
"""))
# Render
template_message = TemplateMessage(template_path)
_, _, message = template_message.render({})
# Verify directory used to render is different from template directory
assert os.getcwd() != tmpdir
# Verify attachment
attachments = extract_attachments(message)
filename, content = attachments[0]
assert filename == "attachment.txt"
assert content == b"Hello world\n"
def test_attachment_absolute(tmpdir):
"""Attachment with absolute file path."""
# Simple attachment lives in sub directory
attachments_dir = tmpdir.mkdir("attachments")
attachment_path = Path(attachments_dir/"attachment.txt")
attachment_path.write_text(u"Hello world\n")
# Simple template
template_path = Path(tmpdir/"template.txt")
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
FROM: from@test.com
ATTACHMENT: {filename}
Hello world
""".format(filename=attachment_path)))
# Render in tmpdir
with tmpdir.as_cwd():
template_message = TemplateMessage(template_path)
_, _, message = template_message.render({})
# Verify attachment
attachments = extract_attachments(message)
filename, content = attachments[0]
assert filename == "attachment.txt"
assert content == b"Hello world\n"
def test_attachment_template(tmpdir):
"""Attachment with template as part of file path."""
# Simple attachment lives in sub directory
attachments_dir = tmpdir.mkdir("attachments")
attachment_path = Path(attachments_dir/"attachment.txt")
attachment_path.write_text(u"Hello world\n")
# Simple template
template_path = Path(tmpdir/"template.txt")
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
FROM: from@test.com
ATTACHMENT: {{filename}}
Hello world
"""))
# Render in tmpdir
with tmpdir.as_cwd():
template_message = TemplateMessage(template_path)
_, _, message = template_message.render({
"filename": str(attachment_path),
})
# Verify attachment
attachments = extract_attachments(message)
filename, content = attachments[0]
assert filename == "attachment.txt"
assert content == b"Hello world\n"
def test_attachment_not_found(tmpdir):
"""Attachment file not found."""
# Template specifying an attachment that doesn't exist
template_path = Path(tmpdir/"template.txt")
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
FROM: from@test.com
ATTACHMENT: attachment.txt
Hello world
"""))
# Render in tmpdir, which lacks attachment.txt
template_message = TemplateMessage(template_path)
with pytest.raises(MailmergeError):
with tmpdir.as_cwd():
template_message.render({})
def test_attachment_blank(tmpdir):
"""Attachment header without a filename is an error."""
template_path = Path(tmpdir/"template.txt")
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
FROM: from@test.com
ATTACHMENT:
Hello world
"""))
template_message = TemplateMessage(template_path)
with pytest.raises(MailmergeError) as err:
with tmpdir.as_cwd():
template_message.render({})
assert "Empty attachment header" in str(err)
def test_attachment_tilde_path(tmpdir):
"""Attachment with home directory tilde notation file path."""
template_path = Path(tmpdir/"template.txt")
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
FROM: from@test.com
ATTACHMENT: ~/attachment.txt
Hello world
"""))
# Render will throw an error because we didn't create a file in the
# user's home directory. We'll just check the filename.
template_message = TemplateMessage(template_path)
with pytest.raises(MailmergeError) as err:
template_message.render({})
correct_path = Path.home() / "attachment.txt"
assert str(correct_path) in str(err)
def test_attachment_multiple(tmp_path):
"""Verify multiple attachments."""
# Copy attachments to tmp dir
shutil.copy(str(utils.TESTDATA/"attachment_1.txt"), str(tmp_path))
shutil.copy(str(utils.TESTDATA/"attachment_2.pdf"), str(tmp_path))
shutil.copy(str(utils.TESTDATA/"attachment_17.txt"), str(tmp_path))
# Create template .txt file
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: {{email}}
SUBJECT: Testing mailmerge
FROM: My Self <myself@mydomain.com>
ATTACHMENT: attachment_1.txt
ATTACHMENT: attachment_2.pdf
ATTACHMENT: attachment_{{number}}.txt
Hi, {{name}},
Your number is {{number}}.
"""))
template_message = TemplateMessage(template_path)
sender, recipients, message = template_message.render({
"email": "myself@mydomain.com",
"name": "Myself",
"number": 17,
})
# Verify sender and recipients
assert sender == "My Self <myself@mydomain.com>"
assert recipients == ["myself@mydomain.com"]
# Verify message is multipart
assert message.is_multipart()
# Make sure the attachments are all present and valid
email_body_present = False
expected_attachments = {
"attachment_1.txt": False,
"attachment_2.pdf": False,
"attachment_17.txt": False,
}
for part in message.walk():
if part.get_content_maintype() == 'multipart':
continue
if part['content-type'].startswith('text/plain'):
# This is the email body
email_body = part.get_payload()
assert email_body.rstrip() == 'Hi, Myself,\n\nYour number is 17.'
email_body_present = True
elif part['content-type'].startswith('application/octet-stream'):
# This is an attachment
filename = part.get_param('name')
file_contents = part.get_payload(decode=True)
assert filename in expected_attachments
assert not expected_attachments[filename]
with (utils.TESTDATA/filename).open('rb') as expected_attachment:
correct_file_contents = expected_attachment.read()
assert file_contents == correct_file_contents
expected_attachments[filename] = True
assert email_body_present
assert False not in expected_attachments.values()
def test_attachment_empty(tmp_path):
"""Errr on empty attachment field."""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
SUBJECT: Testing mailmerge
FROM: from@test.com
ATTACHMENT:
Hello world
"""))
template_message = TemplateMessage(template_path)
with pytest.raises(MailmergeError):
template_message.render({})
def test_utf8_template(tmp_path):
"""Verify UTF8 support in email template."""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
SUBJECT: Testing mailmerge
FROM: from@test.com
From the Tagelied of Wolfram von Eschenbach (Middle High German):
S卯ne kl芒wen durh die wolken sint geslagen,
er st卯get 没f mit gr么zer kraft,
ich sih in gr芒wen t盲gel卯ch als er wil tagen,
den tac, der im geselleschaft
erwenden wil, dem werden man,
den ich mit sorgen 卯n verliez.
ich bringe in hinnen, ob ich kan.
s卯n vil manegiu tugent michz leisten hiez.
http://www.columbia.edu/~fdc/utf8/
"""))
template_message = TemplateMessage(template_path)
sender, recipients, message = template_message.render({
"email": "myself@mydomain.com",
})
# Verify encoding
assert message.get_content_maintype() == "text"
assert message.get_content_subtype() == "plain"
assert message.get_content_charset() == "utf-8"
# Verify sender and recipients
assert sender == "from@test.com"
assert recipients == ["to@test.com"]
# Verify content
plaintext = message.get_payload(decode=True).decode("utf-8")
assert plaintext == textwrap.dedent(u"""\
From the Tagelied of Wolfram von Eschenbach (Middle High German):
S卯ne kl芒wen durh die wolken sint geslagen,
er st卯get 没f mit gr么zer kraft,
ich sih in gr芒wen t盲gel卯ch als er wil tagen,
den tac, der im geselleschaft
erwenden wil, dem werden man,
den ich mit sorgen 卯n verliez.
ich bringe in hinnen, ob ich kan.
s卯n vil manegiu tugent michz leisten hiez.
http://www.columbia.edu/~fdc/utf8/""")
def test_utf8_database(tmp_path):
"""Verify UTF8 support when template is rendered with UTF-8 value."""
# Simple template
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
FROM: from@test.com
Hi {{name}}
"""))
# Render template with context containing unicode characters
template_message = TemplateMessage(template_path)
sender, recipients, message = template_message.render({
"name": u"La葷amon",
})
# Verify sender and recipients
assert sender == "from@test.com"
assert recipients == ["to@test.com"]
# Verify message encoding. The template was ASCII, but when the template
# is rendered with UTF-8 data, the result is UTF-8 encoding.
assert message.get_content_maintype() == "text"
assert message.get_content_subtype() == "plain"
assert message.get_content_charset() == "utf-8"
# Verify content
plaintext = message.get_payload(decode=True).decode("utf-8")
assert plaintext == u"Hi La葷amon"
def test_emoji(tmp_path):
"""Verify emoji are encoded."""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: test@test.com
SUBJECT: Testing mailmerge
FROM: test@test.com
Hi 馃榾
""")) # grinning face emoji
template_message = TemplateMessage(template_path)
_, _, message = template_message.render({})
# Verify encoding
assert message.get_charset() == "utf-8"
assert message["Content-Transfer-Encoding"] == "base64"
# Verify content
plaintext = message.get_payload(decode=True).decode("utf-8")
assert plaintext == u"Hi 馃榾"
def test_emoji_markdown(tmp_path):
"""Verify emoji are encoded in Markdown formatted messages."""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: test@example.com
SUBJECT: Testing mailmerge
FROM: test@example.com
CONTENT-TYPE: text/markdown
```
emoji_string = 馃榾
```
""")) # grinning face emoji
template_message = TemplateMessage(template_path)
_, _, message = template_message.render({})
# Message should contain an unrendered Markdown plaintext part and a
# rendered Markdown HTML part
plaintext_part, html_part = message.get_payload()
# Verify encodings
assert str(plaintext_part.get_charset()) == "utf-8"
assert str(html_part.get_charset()) == "utf-8"
assert plaintext_part["Content-Transfer-Encoding"] == "base64"
assert html_part["Content-Transfer-Encoding"] == "base64"
# Verify content, which is base64 encoded grinning face emoji
plaintext = plaintext_part.get_payload(decode=True).decode("utf-8")
htmltext = html_part.get_payload(decode=True).decode("utf-8")
assert plaintext == u'```\nemoji_string = \U0001f600\n```'
assert htmltext == (
u"<html><body><p><code>"
u"emoji_string = \U0001f600"
u"</code></p></body></html>"
)
def test_emoji_database(tmp_path):
"""Verify emoji are encoded when they are substituted via template db.
The template is ASCII encoded, but after rendering the template, an emoji
character will substituted into the template. The result should be a utf-8
encoded message.
"""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: test@test.com
SUBJECT: Testing mailmerge
FROM: test@test.com
Hi {{emoji}}
"""))
template_message = TemplateMessage(template_path)
_, _, message = template_message.render({
"emoji": u"馃榾" # grinning face
})
# Verify encoding
assert message.get_charset() == "utf-8"
assert message["Content-Transfer-Encoding"] == "base64"
# Verify content
plaintext = message.get_payload(decode=True).decode("utf-8")
assert plaintext == u"Hi 馃榾"
def test_encoding_us_ascii(tmp_path):
"""Render a simple template with us-ascii encoding."""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
FROM: from@test.com
Hello world
"""))
template_message = TemplateMessage(template_path)
_, _, message = template_message.render({})
assert message.get_charset() == "us-ascii"
assert message.get_content_charset() == "us-ascii"
assert message.get_payload() == "Hello world"
def test_encoding_utf8(tmp_path):
"""Render a simple template with UTF-8 encoding."""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
FROM: from@test.com
Hello La葷amon
"""))
template_message = TemplateMessage(template_path)
_, _, message = template_message.render({})
assert message.get_charset() == "utf-8"
assert message.get_content_charset() == "utf-8"
plaintext = message.get_payload(decode=True).decode("utf-8")
assert plaintext == u"Hello La葷amon"
def test_encoding_is8859_1(tmp_path):
"""Render a simple template with IS8859-1 encoding.
Mailmerge will coerce the encoding to UTF-8.
"""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
FROM: from@test.com
Hello L'Ha每-les-Roses
"""))
template_message = TemplateMessage(template_path)
_, _, message = template_message.render({})
assert message.get_charset() == "utf-8"
assert message.get_content_charset() == "utf-8"
plaintext = message.get_payload(decode=True).decode("utf-8")
assert plaintext == u"Hello L'Ha每-les-Roses"
def test_encoding_mismatch(tmp_path):
"""Render a simple template that lies about its encoding.
Header says us-ascii, but it contains utf-8.
"""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
FROM: from@test.com
Content-Type: text/plain; charset="us-ascii"
Hello La葷amon
"""))
template_message = TemplateMessage(template_path)
_, _, message = template_message.render({})
assert message.get_charset() == "utf-8"
assert message.get_content_charset() == "utf-8"
plaintext = message.get_payload(decode=True).decode("utf-8")
assert plaintext == u"Hello La葷amon"
def test_encoding_multipart(tmp_path):
"""Render a utf-8 template with multipart encoding."""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
FROM: from@test.com
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="boundary"
This is a MIME-encoded message. If you are seeing this, your mail
reader is old.
--boundary
Content-Type: text/plain; charset=utf-8
Hello La葷amon
--boundary
Content-Type: text/html; charset=utf-8
<html>
<body>
<p>Hello La葷amon</p>
</body>
</html>
"""))
template_message = TemplateMessage(template_path)
sender, recipients, message = template_message.render({})
# Verify sender and recipients
assert sender == "from@test.com"
assert recipients == ["to@test.com"]
# Should be multipart: plaintext and HTML
assert message.is_multipart()
parts = message.get_payload()
assert len(parts) == 2
plaintext_part, html_part = parts
# Verify plaintext part
assert plaintext_part.get_charset() == "utf-8"
assert plaintext_part.get_content_charset() == "utf-8"
assert plaintext_part.get_content_type() == "text/plain"
plaintext = plaintext_part.get_payload(decode=True).decode("utf-8")
plaintext = plaintext.strip()
assert plaintext == u"Hello La葷amon"
# Verify html part
assert html_part.get_charset() == "utf-8"
assert html_part.get_content_charset() == "utf-8"
assert html_part.get_content_type() == "text/html"
htmltext = html_part.get_payload(decode=True).decode("utf-8")
htmltext = re.sub(r"\s+", "", htmltext) # Strip whitespace
assert htmltext == u"<html><body><p>HelloLa葷amon</p></body></html>"
def test_encoding_multipart_mismatch(tmp_path):
"""Render a utf-8 template with multipart encoding and wrong headers.
Content-Type headers say "us-ascii", but the message contains utf-8.
"""
template_path = tmp_path / "template.txt"
template_path.write_text(textwrap.dedent(u"""\
TO: to@test.com
FROM: from@test.com
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="boundary"
This is a MIME-encoded message. If you are seeing this, your mail
reader is old.
--boundary
Content-Type: text/plain; charset=us-ascii
Hello La葷amon
--boundary
Content-Type: text/html; charset=us-ascii
<html>
<body>
<p>Hello La葷amon</p>
</body>
</html>
"""))
template_message = TemplateMessage(template_path)
sender, recipients, message = template_message.render({})
# Verify sender and recipients
assert sender == "from@test.com"
assert recipients == ["to@test.com"]
# Should be multipart: plaintext and HTML
assert message.is_multipart()
parts = message.get_payload()
assert len(parts) == 2
plaintext_part, html_part = parts
# Verify plaintext part
assert plaintext_part.get_charset() == "utf-8"
assert plaintext_part.get_content_charset() == "utf-8"
assert plaintext_part.get_content_type() == "text/plain"
plaintext = plaintext_part.get_payload(decode=True).decode("utf-8")
plaintext = plaintext.strip()
assert plaintext == u"Hello La葷amon"
# Verify html part
assert html_part.get_charset() == "utf-8"
assert html_part.get_content_charset() == "utf-8"
assert html_part.get_content_type() == "text/html"
htmltext = html_part.get_payload(decode=True).decode("utf-8")
htmltext = re.sub(r"\s+", "", htmltext) # Strip whitespace
assert htmltext == u"<html><body><p>HelloLa葷amon</p></body></html>"