1 package org.apache.maven.announcement;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 import java.io.PrintWriter;
22 import java.io.Writer;
23 import java.util.StringTokenizer;
24
25 import org.apache.commons.net.smtp.SMTPClient;
26 import org.apache.commons.net.smtp.SMTPReply;
27 import org.apache.commons.net.smtp.SimpleSMTPHeader;
28
29 /**
30 * Send an email message using Jakarta Commons Net
31 * @author Felipe Leme
32 * @version $Id: MailUtils.java 529166 2007-04-16 08:31:26Z ltheussl $
33 */
34 public class MailUtils
35 {
36 /** E-mail address separator. */
37 private static final String ADDRESS_SEPARATOR = ",";
38
39 /**
40 * Send an email message.
41 *
42 * @param server The server
43 * @param client The client
44 * @param from from e-mail address
45 * @param to to e-mail address
46 * @param subject e-mail subject
47 * @param msg e-mail body
48 * @return "ok" if everything is fine, the Exception error message otherwise
49 */
50 public static String sendMail(String server, String client,
51 String from, String to, String subject, String msg)
52 {
53
54 if (server == null)
55 {
56 return "no smtp server configured";
57 }
58 if (client == null)
59 {
60 return "no smtp client configured";
61 }
62 if (to == null)
63 {
64 return "no to address specified";
65 }
66 if (from == null)
67 {
68 return "no from address specified";
69 }
70 if (msg == null)
71 {
72 return "no message specified";
73 }
74 if (subject == null)
75 {
76 return "no subject specified";
77 }
78
79
80 SMTPClient smtpClient = new SMTPClient();
81 System.out.println("Connecting to SMTP Server [" + server + "]");
82 try
83 {
84 smtpClient.connect(server);
85
86 int reply = smtpClient.getReplyCode();
87 if (!SMTPReply.isPositiveCompletion(reply))
88 {
89 smtpClient.disconnect();
90 return "SMTP server [" + server + "] refused connection.";
91 }
92
93 smtpClient.login(client);
94
95 smtpClient.setSender(from);
96
97 StringTokenizer st = new StringTokenizer(to.toString(),
98 ADDRESS_SEPARATOR);
99 while (st.hasMoreTokens())
100 {
101 smtpClient.addRecipient(st.nextToken().trim());
102 }
103
104 System.out.println("Sending message from [" + from + "] to ["
105 + to + "]");
106
107
108 Writer clientWriter = smtpClient.sendMessageData();
109 if (clientWriter == null)
110 {
111 return "Could not send data to the SMTP server";
112 }
113 PrintWriter writer = new PrintWriter(clientWriter);
114 SimpleSMTPHeader header = new SimpleSMTPHeader(from, to, subject);
115
116
117
118
119
120 writer.write(header.toString());
121
122
123 writer.write(msg);
124
125
126 writer.close();
127 if (!smtpClient.completePendingCommand())
128 {
129 return "Could not send the SMTP message";
130 }
131
132
133 smtpClient.logout();
134
135
136 smtpClient.disconnect();
137
138
139 return "ok";
140 }
141 catch (Exception e)
142 {
143 e.printStackTrace();
144 return e.getMessage();
145 }
146 }
147
148 }