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.wire;
31
32 import com.icegreen.greenmail.util.GreenMail;
33 import com.icegreen.greenmail.util.ServerSetup;
34 import com.jcabi.email.Envelope;
35 import com.jcabi.email.Postman;
36 import com.jcabi.email.Protocol;
37 import com.jcabi.email.Token;
38 import com.jcabi.email.enclosure.EnHtml;
39 import com.jcabi.email.enclosure.EnPlain;
40 import com.jcabi.email.stamp.StBcc;
41 import com.jcabi.email.stamp.StCc;
42 import com.jcabi.email.stamp.StRecipient;
43 import com.jcabi.email.stamp.StSender;
44 import com.jcabi.email.stamp.StSubject;
45 import java.io.IOException;
46 import java.net.ServerSocket;
47 import javax.mail.Message;
48 import javax.mail.internet.InternetAddress;
49 import javax.mail.internet.MimeMessage;
50 import org.hamcrest.MatcherAssert;
51 import org.hamcrest.Matchers;
52 import org.junit.Test;
53
54
55
56
57
58
59
60
61 public final class SmtpTest {
62
63
64
65
66
67 @Test
68 public void sendsEmailToSmtpServer() throws Exception {
69 final String bind = "localhost";
70 final int received = 3;
71 final int port = SmtpTest.port();
72 final int timeout = 3000;
73 final ServerSetup setup = new ServerSetup(
74 port, bind, ServerSetup.PROTOCOL_SMTP
75 );
76 setup.setServerStartupTimeout(timeout);
77 final GreenMail server = new GreenMail(setup);
78 server.start();
79 try {
80 new Postman.Default(
81 new Smtp(
82 new Token("", "")
83 .access(new Protocol.Smtp(bind, port))
84 )
85 ).send(
86 new Envelope.Safe(
87 new Envelope.Mime()
88 .with(new StSender("from <test-from@jcabi.com>"))
89 .with(new StRecipient("to", "test-to@jcabi.com"))
90 .with(new StCc(new InternetAddress("cc <c@jcabi.com>")))
91 .with(new StBcc("bcc <bcc@jcabi.com>"))
92 .with(new StSubject("test subject: test me"))
93 .with(new EnPlain("hello"))
94 .with(new EnHtml("<p>how are you?</p>"))
95 )
96 );
97 final MimeMessage[] messages = server.getReceivedMessages();
98 MatcherAssert.assertThat(
99 messages.length,
100 Matchers.is(received)
101 );
102 for (final Message msg : messages) {
103 MatcherAssert.assertThat(
104 msg.getFrom()[0].toString(),
105 Matchers.containsString("<test-from@jcabi.com>")
106 );
107 MatcherAssert.assertThat(
108 msg.getSubject(),
109 Matchers.containsString("test me")
110 );
111 }
112 } finally {
113 server.stop();
114 }
115 }
116
117
118
119
120
121
122 private static int port() throws IOException {
123 try (ServerSocket socket = new ServerSocket(0)) {
124 return socket.getLocalPort();
125 }
126 }
127
128 }