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 StRecipientTest {
51
52
53
54
55
56 @Test
57 public void addsRecipientToMessage() throws Exception {
58 final Message msg = new MimeMessage(
59 Session.getDefaultInstance(new Properties())
60 );
61 new StRecipient(
62 "Jeff Петровский", "jeff@gmail.com"
63 ).attach(msg);
64 MatcherAssert.assertThat(
65 new InternetAddress(
66 msg.getRecipients(Message.RecipientType.TO)[0].toString()
67 ).getAddress(),
68 Matchers.endsWith("@gmail.com")
69 );
70 }
71
72
73
74
75
76 @Test
77 public void addsRecipientToMessageWithCustomCharset() throws Exception {
78 final String charset = "KOI8-R";
79 final Message msg = new MimeMessage(
80 Session.getDefaultInstance(new Properties())
81 );
82 final String name = "Ivan Иванов";
83 final String family = "Иванов";
84 new StRecipient(name, "ivan@gmail.com", charset).attach(msg);
85 MatcherAssert.assertThat(
86 new InternetAddress(
87 msg.getRecipients(Message.RecipientType.TO)[0].toString()
88 ).getPersonal(),
89 Matchers.containsString(family)
90 );
91 MatcherAssert.assertThat(
92 msg.getRecipients(Message.RecipientType.TO)[0].toString(),
93 Matchers.not(Matchers.containsString(family))
94 );
95 MatcherAssert.assertThat(
96 msg.getRecipients(Message.RecipientType.TO)[0].toString(),
97 Matchers.not(Matchers.containsString("UTF"))
98 );
99 MatcherAssert.assertThat(
100 msg.getRecipients(Message.RecipientType.TO)[0].toString(),
101 Matchers.containsString(charset)
102 );
103 MatcherAssert.assertThat(
104 msg.getRecipients(Message.RecipientType.TO)[0].toString(),
105 Matchers.containsString(encodeText(name, charset))
106 );
107 }
108
109
110
111
112
113
114
115
116 private static String encodeText(
117 final String text,
118 final String charset
119 ) throws UnsupportedEncodingException {
120 final String encoded = MimeUtility.encodeWord(text, charset, null);
121 final int last = encoded.lastIndexOf('?');
122 final int prev = encoded.lastIndexOf('?', last - 1);
123 return encoded.substring(prev + 1, last);
124 }
125
126 }