List of usage examples for org.apache.commons.net.smtp SMTPReply isPositiveCompletion
public static boolean isPositiveCompletion(int reply)
From source file:examples.mail.java
public final static void main(String[] args) { String sender, recipient, subject, filename, server, cc; Vector ccList = new Vector(); BufferedReader stdin;/*from w w w . ja v a2 s. co m*/ FileReader fileReader = null; Writer writer; SimpleSMTPHeader header; SMTPClient client; Enumeration en; if (args.length < 1) { System.err.println("Usage: mail smtpserver"); System.exit(1); } server = args[0]; stdin = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("From: "); System.out.flush(); sender = stdin.readLine(); System.out.print("To: "); System.out.flush(); recipient = stdin.readLine(); System.out.print("Subject: "); System.out.flush(); subject = stdin.readLine(); header = new SimpleSMTPHeader(sender, recipient, subject); while (true) { System.out.print("CC <enter one address per line, hit enter to end>: "); System.out.flush(); // Of course you don't want to do this because readLine() may be null cc = stdin.readLine().trim(); if (cc.length() == 0) break; header.addCC(cc); ccList.addElement(cc); } System.out.print("Filename: "); System.out.flush(); filename = stdin.readLine(); try { fileReader = new FileReader(filename); } catch (FileNotFoundException e) { System.err.println("File not found. " + e.getMessage()); } client = new SMTPClient(); client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); client.connect(server); if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) { client.disconnect(); System.err.println("SMTP server refused connection."); System.exit(1); } client.login(); client.setSender(sender); client.addRecipient(recipient); en = ccList.elements(); while (en.hasMoreElements()) client.addRecipient((String) en.nextElement()); writer = client.sendMessageData(); if (writer != null) { writer.write(header.toString()); Util.copyReader(fileReader, writer); writer.close(); client.completePendingCommand(); } fileReader.close(); client.logout(); client.disconnect(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } }
From source file:com.xiangzhurui.util.email.SMTPMail.java
public static void main(String[] args) { String sender, recipient, subject, filename, server, cc; List<String> ccList = new ArrayList<String>(); BufferedReader stdin;//from w ww. j a v a2 s. c o m FileReader fileReader = null; Writer writer; SimpleSMTPHeader header; SMTPClient client; if (args.length < 1) { System.err.println("Usage: mail smtpserver"); System.exit(1); } server = args[0]; stdin = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("From: "); System.out.flush(); sender = stdin.readLine(); System.out.print("To: "); System.out.flush(); recipient = stdin.readLine(); System.out.print("Subject: "); System.out.flush(); subject = stdin.readLine(); header = new SimpleSMTPHeader(sender, recipient, subject); while (true) { System.out.print("CC <enter one address per line, hit enter to end>: "); System.out.flush(); cc = stdin.readLine(); if (cc == null || cc.length() == 0) { break; } header.addCC(cc.trim()); ccList.add(cc.trim()); } System.out.print("Filename: "); System.out.flush(); filename = stdin.readLine(); try { fileReader = new FileReader(filename); } catch (FileNotFoundException e) { System.err.println("File not found. " + e.getMessage()); } client = new SMTPClient(); client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); client.connect(server); if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) { client.disconnect(); System.err.println("SMTP server refused connection."); System.exit(1); } client.login(); client.setSender(sender); client.addRecipient(recipient); for (String recpt : ccList) { client.addRecipient(recpt); } writer = client.sendMessageData(); if (writer != null) { writer.write(header.toString()); Util.copyReader(fileReader, writer); writer.close(); client.completePendingCommand(); } if (fileReader != null) { fileReader.close(); } client.logout(); client.disconnect(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } }
From source file:com.discursive.jccook.net.SMTPExample.java
public void start() throws SocketException, IOException { SMTPClient client = new SMTPClient(); client.connect("www.discursive.com"); int response = client.getReplyCode(); if (SMTPReply.isPositiveCompletion(response)) { client.setSender("tobrien@discursive.com"); client.addRecipient("tobrien@iesabroad.org"); Writer message = client.sendMessageData(); message.write("This is a test message"); message.close();//from w w w .jav a 2 s .c om boolean success = client.completePendingCommand(); if (success) { System.out.println("Message sent"); } } else { System.out.println("Error communicating with SMTP server"); } client.disconnect(); }
From source file:emailchecker.CheckEmailObj.java
public boolean checkEmail(String email) { if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) { System.err.println("Format error"); return false; }/*from w w w .j a va2s . co m*/ // String log = ""; String host = ""; String hostName = email.split("@")[1]; Record[] result = null; SMTPClient client = new SMTPClient(); try { // MX Lookup lookup = new Lookup(hostName, Type.MX); lookup.run(); if (lookup.getResult() != Lookup.SUCCESSFUL) { log += "?MX\n"; return false; } else { result = lookup.getAnswers(); } // ? for (int i = 0; i < result.length; i++) { host = result[i].getAdditionalName().toString(); client.connect(host); if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) { client.disconnect(); continue; } else { log += "MX record about " + hostName + " exists.\n"; log += "Connection succeeded to " + host + "\n"; break; } } log += client.getReplyString(); // HELO cyou-inc.com client.login("cyou-inc.com"); log += ">HELO cyou-inc.com\n"; log += "=" + client.getReplyString(); // MAIL FROM: <zhaojinglun@cyou-inc.com> client.setSender("zhaojinglun@cyou-inc.com"); log += ">MAIL FROM: <zhaojinglun@cyou-inc.com>\n"; log += "=" + client.getReplyString(); // RCPT TO: <$email> client.addRecipient(email); log += ">RCPT TO: <" + email + ">\n"; log += "=" + client.getReplyString() + "\n\n"; if (250 == client.getReplyCode()) { return true; } } catch (Exception e) { e.printStackTrace(); } finally { try { client.disconnect(); } catch (IOException e) { } // ? // System.err.println(log); } return false; }
From source file:com.Module.RegisterModule.java
public static boolean checkEmail(String email) { if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) { return false; }/*from w ww .j a va 2s.c om*/ String host = ""; String hostName = email.split("@")[1]; Record[] result = null; SMTPClient client = new SMTPClient(); try { // MX Lookup lookup = new Lookup(hostName, Type.MX); lookup.run(); if (lookup.getResult() != Lookup.SUCCESSFUL) { return false; } else { result = lookup.getAnswers(); } // ? for (int i = 0; i < result.length; i++) { host = result[i].getAdditionalName().toString(); client.connect(host); if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) { client.disconnect(); continue; } else { break; } } //2 client.login("qq.com"); client.setSender("526199427@163.com"); client.addRecipient(email); if (250 == client.getReplyCode()) { return true; } } catch (Exception e) { e.printStackTrace(); } finally { try { client.disconnect(); } catch (IOException e) { } } return false; }
From source file:com.clustercontrol.port.protocol.ReachAddressSMTP.java
/** * SMTP????????/*from ww w . ja v a2s .c o m*/ * * @param addressText * @return SMTP */ @Override protected boolean isRunning(String addressText) { m_message = ""; m_messageOrg = ""; m_response = -1; boolean isReachable = false; try { long start = 0; // long end = 0; // boolean retry = true; // ????(true:??false:???) StringBuffer bufferOrg = new StringBuffer(); // String result = ""; InetAddress address = InetAddress.getByName(addressText); bufferOrg.append("Monitoring the SMTP Service of " + address.getHostName() + "[" + address.getHostAddress() + "]:" + m_portNo + ".\n\n"); SMTPClient client = new SMTPClient(); for (int i = 0; i < m_sentCount && retry; i++) { try { bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: "); client.setDefaultTimeout(m_timeout); start = HinemosTime.currentTimeMillis(); client.connect(address, m_portNo); end = HinemosTime.currentTimeMillis(); m_response = end - start; result = client.getReplyString(); int reply = client.getReplyCode(); if (SMTPReply.isPositiveCompletion(reply)) { if (m_response > 0) { if (m_response < m_timeout) { result = result + ("\n" + "Response Time = " + m_response + "ms"); } else { m_response = m_timeout; result = result + ("\n" + "Response Time = " + m_response + "ms"); } } else { result = result + ("\n" + "Response Time < 1ms"); } retry = false; isReachable = true; } else { retry = false; isReachable = false; } } catch (SocketException e) { result = (e.getMessage() + "[SocketException]"); retry = true; isReachable = false; } catch (IOException e) { result = (e.getMessage() + "[IOException]"); retry = true; isReachable = false; } finally { bufferOrg.append(result + "\n"); if (client.isConnected()) { try { client.disconnect(); } catch (IOException e) { m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e); } } } if (i < m_sentCount - 1 && retry) { try { Thread.sleep(m_sentInterval); } catch (InterruptedException e) { break; } } } m_message = result + "(SMTP/" + m_portNo + ")"; m_messageOrg = bufferOrg.toString(); return isReachable; } catch (UnknownHostException e) { m_log.warn("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + e.getMessage(), e); m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage() + ")"; return false; } }
From source file:com.clustercontrol.port.protocol.ReachAddressSMTPS.java
/** * SMTPS????????//from w w w . j a v a2 s . c om * * @param addressText * @return SMTPS */ @Override protected boolean isRunning(String addressText) { m_message = ""; m_messageOrg = ""; m_response = -1; boolean isReachable = false; try { long start = 0; // long end = 0; // boolean retry = true; // ????(true:??false:???) StringBuffer bufferOrg = new StringBuffer(); // String result = ""; InetAddress address = InetAddress.getByName(addressText); bufferOrg.append("Monitoring the SMTPS Service of " + address.getHostName() + "[" + address.getHostAddress() + "]:" + m_portNo + ".\n\n"); SMTPSClient client = new SMTPSClient(true); for (int i = 0; i < m_sentCount && retry; i++) { try { bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: "); client.setDefaultTimeout(m_timeout); start = HinemosTime.currentTimeMillis(); client.connect(address, m_portNo); end = HinemosTime.currentTimeMillis(); m_response = end - start; result = client.getReplyString(); int reply = client.getReplyCode(); if (SMTPReply.isPositiveCompletion(reply)) { if (m_response > 0) { if (m_response < m_timeout) { result = result + ("\n" + "Response Time = " + m_response + "ms"); } else { m_response = m_timeout; result = result + ("\n" + "Response Time = " + m_response + "ms"); } } else { result = result + ("\n" + "Response Time < 1ms"); } retry = false; isReachable = true; } else { retry = false; isReachable = false; } } catch (SocketException e) { result = (e.getMessage() + "[SocketException]"); retry = true; isReachable = false; } catch (IOException e) { result = (e.getMessage() + "[IOException]"); retry = true; isReachable = false; } finally { bufferOrg.append(result + "\n"); if (client.isConnected()) { try { client.disconnect(); } catch (IOException e) { m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e); } } } if (i < m_sentCount - 1 && retry) { try { Thread.sleep(m_sentInterval); } catch (InterruptedException e) { break; } } } m_message = result + "(SMTPS/" + m_portNo + ")"; m_messageOrg = bufferOrg.toString(); return isReachable; } catch (UnknownHostException e) { m_log.warn("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + e.getMessage(), e); m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage() + ")"; return false; } }
From source file:com.adito.notification.smtp.SMTPMessageSink.java
private void connect() throws SocketException, IOException, Exception { if (LOG.isDebugEnabled()) { LOG.debug("Setting timeout"); LOG.debug("Connecting to SMTP server"); }/*from w ww . ja va 2 s .c om*/ String hostname = Property.getProperty(new SystemConfigKey("smtp.hostname")); int port = Property.getPropertyInt(new SystemConfigKey("smtp.port")); client.connect(hostname, port); if (LOG.isDebugEnabled()) { LOG.debug("Getting reply"); } int reply = client.getReplyCode(); if (!SMTPReply.isPositiveCompletion(reply)) { client.disconnect(); throw new Exception("SMTP server refused connection."); } if (LOG.isDebugEnabled()) { LOG.debug("Logging in"); } String helo = Property.getProperty(new SystemConfigKey("smtp.login")); if (helo.equals("")) { client.login(); } else { client.login(helo); } }
From source file:de.burlov.ultracipher.core.mail.AuthenticatingSMTPClient.java
/** * Login to the ESMTP server by sending the EHLO command with the given * hostname as an argument. Before performing any mail commands, you must * first login./*from w ww. j a v a 2s. com*/ * <p/> * * @param hostname The hostname with which to greet the SMTP server. * @return True if successfully completed, false if not. * @throws SMTPConnectionClosedException If the SMTP server prematurely closes the connection as a * result of the client being idle or some other reason * causing the server to send SMTP reply code 421. This * exception may be caught either as an IOException or * independently as itself. * @throws java.io.IOException If an I/O error occurs while either sending a command to * the server or receiving a reply from the server. * * */ public boolean elogin(String hostname) throws IOException { return SMTPReply.isPositiveCompletion(ehlo(hostname)); }
From source file:com.ironiacorp.email.CommonsNetEmailDispatcher.java
@Override public void sendEmails(Email... emails) { AuthenticatingSMTPClient client = null; boolean result = false; int port = connectionType.port; if (serverPort != 0) { port = serverPort;/*from w w w. jav a 2s.c o m*/ } try { client = new AuthenticatingSMTPClient(); client.connect(serverName, port); if (connectionType == EmailServerConnectionType.SSL || connectionType == EmailServerConnectionType.TLS) { result = client.execTLS(); if (result == false) { throw new IllegalArgumentException("Cannot start secure connection"); } } if (authenticationRequired) { result = client.auth(AUTH_METHOD.PLAIN, username, password); if (result == false) { throw new IllegalArgumentException("Incorrect username or password"); } } // After connection attempt, you should check the reply code to verify success. int reply = client.getReplyCode(); if (!SMTPReply.isPositiveCompletion(reply)) { client.disconnect(); } for (Email email : emails) { SimpleSMTPHeader header; Iterator<Recipient> i = email.getRecipients().iterator(); Writer writer = client.sendMessageData(); String to = null; while (i.hasNext()) { Recipient recipient = i.next(); if (to == null && email.getVisibility(recipient) == Visibility.TO) { to = recipient.getEmail(); } else { client.addRecipient(recipient.getEmail()); } } header = new SimpleSMTPHeader(email.getSender().getEmail(), null, email.getSubject()); writer.write(header.toString()); result = client.completePendingCommand(); if (result == false) { throw new IllegalArgumentException("Could not send the email"); } client.reset(); } } catch (Exception e) { throw new UnsupportedOperationException("Could not send the email", e); } finally { if (client != null && client.isConnected()) { try { client.disconnect(); } catch (IOException e) { } } } }