1 package net.jaekl.qd.util;
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import java.io.PrintWriter;
7 import java.net.InetAddress;
8 import java.net.Socket;
9 import java.net.UnknownHostException;
10 import java.nio.charset.Charset;
11 import java.util.ArrayList;
12 import java.util.List;
14 public class SendMail {
15 private static final String RESP_220 = "220"; // server ready
16 private static final String RESP_221 = "221"; // goodbye
17 private static final String RESP_250 = "250"; // success
18 private static final String RESP_251 = "251"; // mail address change (we don't support this)
19 private static final String RESP_354 = "354"; // OK, proceed with DATA transmission
21 // Actually, RFC821 (with which all SMTP should be backwards-compatible)
22 // requires all control transmissions to be done in US-ASCII.
23 // However, there's no point in throwing an exception if the server with which
24 // we're communicating sends bytes with the high bit set. So, let's read from
25 // the socket with the only Charset that Java guarantees will be available that
26 // can also read arbitrary sequences of 8-bit bytes.
27 private static final String SMTP_CHARSET = "ISO-8859-1";
37 ArrayList<String> m_to;
38 ArrayList<String> m_cc;
39 ArrayList<String> m_bcc;
40 ArrayList<MimePart> m_part;
46 m_smtpHost = "localhost";
48 m_from = "noreply@localhost";
50 m_to = new ArrayList<String>();
51 m_cc = new ArrayList<String>();
52 m_bcc = new ArrayList<String>();
53 m_part = new ArrayList<MimePart>();
56 public void setSmtpHost(String hostName) { m_smtpHost = hostName; }
57 public void setSmtpPort(int portNum) { m_smtpPort = portNum; }
58 public void setFrom(String addr) { m_from = addr; }
59 public void setSubject(String subject) { m_subject = subject; }
60 public void addTo(String addr) { m_to.add(addr); }
61 public void addCc(String addr) { m_cc.add(addr); }
62 public void addBcc(String addr) { m_bcc.add(addr); }
63 public void addPart(MimePart part) { m_part.add(part); }
65 public void send() throws MailException
68 Socket sock = openSocket(m_smtpHost, m_smtpPort);
69 PrintWriter pw = new PrintWriter(sock.getOutputStream(), true);
70 BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream(), getCharset()));
75 catch (IOException exc) {
76 throw new MailException(exc);
80 Socket openSocket(String host, int port) throws UnknownHostException, IOException {
81 return new Socket(host, port);
84 String getHostName() throws UnknownHostException {
85 if (null == m_hostName) {
86 m_hostName = InetAddress.getLocalHost().getHostName();
91 void send(PrintWriter pw, BufferedReader br) throws MailException
97 line = readResponse(br);
98 validateResponse("", RESP_220, line);
100 cmd = "HELO " + getHostName();
101 line = sendLine(pw, br, cmd);
102 validateResponse(cmd, RESP_250, line);
104 cmd = "MAIL FROM: " + m_from;
105 line = sendLine(pw, br, cmd);
106 validateResponse(cmd, RESP_250, line);
108 sendRcpt(pw, br, m_to);
109 sendRcpt(pw, br, m_cc);
110 sendRcpt(pw, br, m_bcc);
113 line = sendLine(pw, br, cmd);
114 validateResponse(cmd, RESP_354, line);
116 line = sendData(pw, br);
117 validateResponse(cmd, RESP_250, line);
120 line = sendLine(pw, br, cmd);
121 validateResponse(cmd, RESP_221, line);
123 catch (IOException exc) {
124 throw new MailException(exc);
128 // Send the DATA content of the email
129 String sendData(PrintWriter pw, BufferedReader br) throws MailException, IOException
131 sendLine(pw, "From: " + m_from);
132 sendAddressee(pw, "To", m_to);
133 sendAddressee(pw, "Cc", m_cc);
134 sendAddressee(pw, "Bcc", m_bcc);
135 sendLine(pw, "Subject: " + m_subject);
142 String result = sendLine(pw, br, "\r\n.");
146 void sendMimeHeaders(PrintWriter pw)
148 sendLine(pw, "MIME-Version: 1.0");
149 sendLine(pw, "Content-Type: multipart/mixed; boundary=" + getBoundary());
152 void sendMimeParts(PrintWriter pw) {
153 for (MimePart part : m_part) {
154 sendLine(pw, "--" + getBoundary());
155 sendLine(pw, "Content-Type: " + part.getMimeType()); // TODO: Add support for encodings
157 sendLine(pw, part.getContent());
160 sendLine(pw, "--" + getBoundary() + "--");
163 boolean isBoundaryOk(String candidate) {
164 for (MimePart part : m_part) {
165 if (part.getContent().contains(candidate)) {
172 Charset getCharset() {
173 if (null == m_charset) {
174 m_charset = Charset.forName(SMTP_CHARSET);
181 if (null != m_boundary) {
185 StringBuilder sb = new StringBuilder("snip_snip");
186 if (isBoundaryOk(sb.toString())) {
187 return sb.toString();
194 if (isBoundaryOk(sb.toString())) {
195 m_boundary = sb.toString();
207 void sendAddressee(PrintWriter pw, String designator, List<String> addrs) throws MailException
209 for (String addr : addrs) {
210 sendLine(pw, designator + ": " + addr);
214 void validateResponse(String cmd, String expected, String actual) throws MailException
216 if (! actual.startsWith(expected)) {
217 throw new MailException(cmd, expected, actual);
221 void sendRcpt(PrintWriter pw, BufferedReader br, List<String> addrs) throws IOException, MailException
223 for (String to : addrs) {
224 String cmd = "RCPT TO: " + to;
225 String line = sendLine(pw, br, cmd);
226 if (line.startsWith(RESP_251)) {
227 throw new MailException("Apology: no support for 251 mail forwarding response to RCPT command. Mail will not be delivered: " + line);
229 if (!line.startsWith(RESP_250)) {
230 throw new MailException(cmd, RESP_250, line);
236 // RFC 5321 specifies that all response codes are three digits
237 // at the start of a new line.
238 // These digits may optionally be followed by a space and/or text.
239 // If the response is spread over more than one line, then all but
240 // the last line will have a '-' immediately after the 3rd digit.
242 // This function returns true iff. this line is a response code
243 // that is not continued on the next line.
244 boolean isFinalResponseCode(String line)
250 String trimmed = line.trim();
252 if (trimmed.length() < 3) {
255 if (! ( (Character.isDigit(trimmed.charAt(0)))
256 && (Character.isDigit(trimmed.charAt(1)))
257 && (Character.isDigit(trimmed.charAt(2))) ) )
262 if (3 == trimmed.length()) {
266 if (' ' == trimmed.charAt(3)) {
270 if ('-' == trimmed.charAt(3)) {
271 return false; // This is a response code, but it's continued on the next line
274 // This doesn't look like a response code
278 int responseCode(String line)
280 // RFC 5321 specifies that all response codes are three digits
281 // at the start of a new line.
282 // These digits may optionally be followed by a space and/or text.
284 if ((null == line) || (line.length() < 3)) {
288 return Integer.parseInt(line.substring(0, 3));
291 String readResponse(BufferedReader br) throws IOException
295 while (null != (line = br.readLine())) {
296 if (isFinalResponseCode(line)) {
303 void sendLine(PrintWriter pw, String line)
305 pw.write(line + "\r\n");
309 String sendLine(PrintWriter pw, BufferedReader br, String line) throws IOException
312 return readResponse(br);