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 package com.jcabi.email.stamp;
31
32 import java.io.UnsupportedEncodingException;
33 import java.util.Properties;
34 import javax.mail.Message;
35 import javax.mail.Session;
36 import javax.mail.internet.InternetAddress;
37 import javax.mail.internet.MimeMessage;
38 import javax.mail.internet.MimeUtility;
39 import org.hamcrest.MatcherAssert;
40 import org.hamcrest.Matchers;
41 import org.junit.Test;
42
43
44
45
46
47
48
49
50 public final class StSenderTest {
51
52
53
54
55
56 @Test
57 public void addsSenderToMessage() throws Exception {
58 final Message msg = new MimeMessage(
59 Session.getDefaultInstance(new Properties())
60 );
61 new StSender("Jeff Петровский", "jeff@gmail.com").attach(msg);
62 MatcherAssert.assertThat(
63 new InternetAddress(
64 msg.getFrom()[0].toString()
65 ).getPersonal(),
66 Matchers.containsString("Петровский")
67 );
68 }
69
70
71
72
73
74 @Test
75 public void addsSenderToMessageWithCustomCharset() throws Exception {
76 final String charset = "KOI8-R";
77 final Message msg = new MimeMessage(
78 Session.getDefaultInstance(new Properties())
79 );
80 final String name = "Ivan Иванов";
81 final String family = "Иванов";
82 new StSender(name, "ivan@gmail.com", charset).attach(msg);
83 MatcherAssert.assertThat(
84 new InternetAddress(
85 msg.getFrom()[0].toString()
86 ).getPersonal(),
87 Matchers.containsString(family)
88 );
89 MatcherAssert.assertThat(
90 msg.getFrom()[0].toString(),
91 Matchers.not(Matchers.containsString(family))
92 );
93 MatcherAssert.assertThat(
94 msg.getFrom()[0].toString(),
95 Matchers.not(Matchers.containsString("UTF"))
96 );
97 MatcherAssert.assertThat(
98 msg.getFrom()[0].toString(),
99 Matchers.containsString(charset)
100 );
101 MatcherAssert.assertThat(
102 msg.getFrom()[0].toString(),
103 Matchers.containsString(encodeText(name, charset))
104 );
105 }
106
107
108
109
110
111
112
113
114 private static String encodeText(
115 final String text,
116 final String charset
117 ) throws UnsupportedEncodingException {
118 final String encoded = MimeUtility.encodeWord(text, charset, null);
119 final int last = encoded.lastIndexOf('?');
120 final int prev = encoded.lastIndexOf('?', last - 1);
121 return encoded.substring(prev + 1, last);
122 }
123
124 }