List of usage examples for org.apache.commons.net.smtp SMTPReply isPositiveCompletion
public static boolean isPositiveCompletion(int reply)
From source file:de.burlov.ultracipher.core.mail.AuthenticatingSMTPClient.java
/** * Login to the ESMTP server by sending the EHLO command with the client * hostname as an argument. Before performing any mail commands, you must * first login./*w ww. j a v a2 s .c o m*/ * <p/> * * @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() throws IOException { String name; InetAddress host; host = getLocalAddress(); name = host.getHostName(); if (name == null) { return false; } return SMTPReply.isPositiveCompletion(ehlo(name)); }
From source file:adams.core.net.ApacheSendEmail.java
/** * Sends an email./*w w w .ja va 2 s .com*/ * * @param email the email to send * @return true if successfully sent * @throws Exception in case of invalid internet addresses or messaging problem */ @Override public boolean sendMail(Email email) throws Exception { SimpleSMTPHeader header; int i; Writer writer; String boundary; MediaType mime; byte[] content; String[] lines; if (m_Client == null) throw new IllegalStateException("SMTP session not initialized!"); // header header = new SimpleSMTPHeader(email.getFrom().getValue(), Utils.flatten(email.getTo(), ", "), email.getSubject()); for (i = 0; i < email.getCC().length; i++) header.addCC(email.getCC()[i].getValue()); // create boundary string boundary = EmailHelper.createBoundary(); header.addHeaderField("Content-Type", "multipart/mixed; boundary=" + boundary); // connect m_Client.connect(m_Server, m_Port); if (!SMTPReply.isPositiveCompletion(m_Client.getReplyCode())) { m_Client.disconnect(); getLogger().severe( "SMTP server " + m_Server + ":" + m_Port + " refused connection: " + m_Client.getReplyCode()); return false; } // login if (!m_Client.login()) { m_Client.disconnect(); getLogger().severe("Failed to login to SMTP server " + m_Server + ":" + m_Port + "!"); return false; } // TLS? if (m_UseTLS) { if (!((SMTPSClient) m_Client).execTLS()) { m_Client.logout(); m_Client.disconnect(); getLogger().severe("SMTP server " + m_Server + ":" + m_Port + " failed to start TLS!"); return false; } } // authentication? if (m_RequiresAuth) { if (!((AuthenticatingSMTPClient) m_Client).auth(AuthenticatingSMTPClient.AUTH_METHOD.PLAIN, m_User, m_Password.getValue())) { m_Client.logout(); m_Client.disconnect(); getLogger() .severe("Failed to authenticate: user=" + m_User + ", pw=" + m_Password.getMaskedValue()); return false; } } // fill in recipients m_Client.setSender(email.getFrom().stringValue()); for (i = 0; i < email.getTo().length; i++) m_Client.addRecipient(email.getTo()[i].getValue()); for (i = 0; i < email.getCC().length; i++) m_Client.addRecipient(email.getCC()[i].strippedValue()); for (i = 0; i < email.getBCC().length; i++) m_Client.addRecipient(email.getBCC()[i].stringValue()); // start message writer = m_Client.sendMessageData(); if (writer == null) { m_Client.logout(); m_Client.disconnect(); getLogger().severe("Cannot send data!"); return false; } writer.write(header.toString()); // body writer.write("--" + boundary + "\n"); writer.write("Content-Type: text/plain; charset=ISO-8859-1\n"); writer.write("\n"); writer.write(email.getBody()); writer.write("\n"); writer.write("\n"); // attachements if (email.getAttachments().length > 0) { for (File file : email.getAttachments()) { writer.write("--" + boundary + "\n"); mime = MimeTypeHelper.getMimeType(file); writer.write("Content-Type: " + mime.toString() + "; name=\"" + file.getName() + "\"\n"); writer.write("Content-Disposition: attachment; filename=\"" + file.getName() + "\"\n"); writer.write("Content-Transfer-Encoding: base64\n"); writer.write("\n"); content = FileUtils.loadFromBinaryFile(file); lines = EmailHelper.breakUp(InternetHelper.encodeBase64(content), 76); for (String line : lines) writer.write(line + "\n"); } } // finish message writer.write("--" + boundary + "--\n"); writer.close(); if (!m_Client.completePendingCommand()) { m_Client.logout(); m_Client.disconnect(); getLogger().severe("Failed to complete pending command!"); return false; } m_Client.logout(); m_Client.disconnect(); return true; }
From source file:net.metanotion.emailqueue.SmtpSender.java
@Override public Connection getConnection() { AuthenticatingSMTPClient client = null; try {// www . j a v a 2 s . c om client = new AuthenticatingSMTPClient(); client.addProtocolCommandListener(new ProtocolCommandListener() { @Override public void protocolCommandSent(final ProtocolCommandEvent event) { logger.trace(COMMAND_LOG_FORMAT, event.getCommand(), event.getMessage()); } @Override public void protocolReplyReceived(final ProtocolCommandEvent event) { logger.trace(COMMAND_LOG_FORMAT, event.getCommand(), event.getMessage()); } }); logger.trace("Connecting"); client.connect(this.server, this.port); if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) { logger.error("Did not get positive completion."); throw new IOException("Could not complete SMTP connection."); } startTls(client); logger.trace("Authenticating"); client.auth(AuthenticatingSMTPClient.AUTH_METHOD.PLAIN, username, password); logger.trace("Login"); client.login(host); return new Connection(client); } catch (final IOException | NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException ex) { logger.debug("Error", ex); try { if (client != null) { client.disconnect(); } } catch (final IOException ex2) { } throw new RuntimeException(ex); } }
From source file:de.burlov.ultracipher.core.mail.AuthenticatingSMTPClient.java
/** * Authenticate to the SMTP server by sending the AUTH command with the * selected mechanism, using the given username and the given password. * <p/>// w ww. java 2 s .co m * * @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. * @throws java.security.NoSuchAlgorithmException If the CRAM hash algorithm cannot be instantiated by the * Java runtime system. * @throws java.security.InvalidKeyException If the CRAM hash algorithm failed to use the given * password. * @throws java.security.spec.InvalidKeySpecException If the CRAM hash algorithm failed to use the given * password. * * */ public boolean auth(AUTH_METHOD method, String username, String password) throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException { if (!SMTPReply.isPositiveIntermediate(sendCommand(SMTPCommand.AUTH, AUTH_METHOD.getAuthName(method)))) { return false; } if (method.equals(AUTH_METHOD.PLAIN)) { // the server sends an empty response ("334 "), so we don't have to // read it. return SMTPReply.isPositiveCompletion(sendCommand( new String(Base64.encodeBase64(("\000" + username + "\000" + password).getBytes())))); } else if (method.equals(AUTH_METHOD.CRAM_MD5)) { // get the CRAM challenge byte[] serverChallenge = Base64.decodeBase64(getReplyString().substring(4).trim()); // get the Mac instance Mac hmac_md5 = Mac.getInstance("HmacMD5"); hmac_md5.init(new SecretKeySpec(password.getBytes(), "HmacMD5")); // compute the result: byte[] hmacResult = _convertToHexString(hmac_md5.doFinal(serverChallenge)).getBytes(); // join the byte arrays to form the reply byte[] usernameBytes = username.getBytes(); byte[] toEncode = new byte[usernameBytes.length + 1 /* the space */ + hmacResult.length]; System.arraycopy(usernameBytes, 0, toEncode, 0, usernameBytes.length); toEncode[usernameBytes.length] = ' '; System.arraycopy(hmacResult, 0, toEncode, usernameBytes.length + 1, hmacResult.length); // send the reply and read the server code: return SMTPReply.isPositiveCompletion(sendCommand(new String(Base64.encodeBase64(toEncode)))); } else if (method.equals(AUTH_METHOD.LOGIN)) { // the server sends fixed responses (base64("Username") and // base64("Password")), so we don't have to read them. if (!SMTPReply .isPositiveIntermediate(sendCommand(new String(Base64.encodeBase64(username.getBytes()))))) { return false; } return SMTPReply .isPositiveCompletion(sendCommand(new String(Base64.encodeBase64(password.getBytes())))); } else { return false; // safety check } }
From source file:com.google.gerrit.server.mail.SmtpEmailSender.java
private SMTPClient open() throws EmailException { final AuthSMTPClient client = new AuthSMTPClient("UTF-8"); if (smtpEncryption == Encryption.SSL) { client.enableSSL(sslVerify);//w w w. j a v a2 s . c om } try { client.connect(smtpHost, smtpPort); if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) { throw new EmailException("SMTP server rejected connection"); } if (!client.login()) { String e = client.getReplyString(); throw new EmailException("SMTP server rejected HELO/EHLO greeting: " + e); } if (smtpEncryption == Encryption.TLS) { if (!client.startTLS(smtpHost, smtpPort, sslVerify)) { throw new EmailException("SMTP server does not support TLS"); } if (!client.login()) { String e = client.getReplyString(); throw new EmailException("SMTP server rejected login: " + e); } } if (smtpUser != null && !client.auth(smtpUser, smtpPass)) { String e = client.getReplyString(); throw new EmailException("SMTP server rejected auth: " + e); } } catch (IOException e) { if (client.isConnected()) { try { client.disconnect(); } catch (IOException e2) { } } throw new EmailException(e.getMessage(), e); } catch (EmailException e) { if (client.isConnected()) { try { client.disconnect(); } catch (IOException e2) { } } throw e; } return client; }
From source file:com.google.gerrit.server.mail.send.SmtpEmailSender.java
private SMTPClient open() throws EmailException { final AuthSMTPClient client = new AuthSMTPClient(UTF_8.name()); if (smtpEncryption == Encryption.SSL) { client.enableSSL(sslVerify);//w w w .ja v a 2 s . c o m } client.setConnectTimeout(connectTimeout); try { client.connect(smtpHost, smtpPort); int replyCode = client.getReplyCode(); String replyString = client.getReplyString(); if (!SMTPReply.isPositiveCompletion(replyCode)) { throw new EmailException( String.format("SMTP server rejected connection: %d: %s", replyCode, replyString)); } if (!client.login()) { throw new EmailException("SMTP server rejected HELO/EHLO greeting: " + replyString); } if (smtpEncryption == Encryption.TLS) { if (!client.startTLS(smtpHost, smtpPort, sslVerify)) { throw new EmailException("SMTP server does not support TLS"); } if (!client.login()) { throw new EmailException("SMTP server rejected login: " + replyString); } } if (smtpUser != null && !client.auth(smtpUser, smtpPass)) { throw new EmailException("SMTP server rejected auth: " + replyString); } return client; } catch (IOException | EmailException e) { if (client.isConnected()) { try { client.disconnect(); } catch (IOException e2) { //Ignored } } if (e instanceof EmailException) { throw (EmailException) e; } throw new EmailException(e.getMessage(), e); } }
From source file:me.schiz.jmeter.protocol.smtp.sampler.SMTPSampler.java
private void setSuccessfulByResponseCode(SampleResult sr, int replyCode) { if (SMTPReply.isPositiveCompletion(replyCode) || SMTPReply.isPositiveIntermediate(replyCode) || SMTPReply.isPositivePreliminary(replyCode)) { sr.setSuccessful(true);//from ww w.j a va2 s . co m } else sr.setSuccessful(false); }
From source file:ProtocolRunner.java
private static void handleSMTP( SMTPClient client, //from w w w . j a v a 2 s.co m ProtocolRunner runner, String commandString) throws IOException { if(commandString == null) { // means just connected // check if the server response was valid if(!SMTPReply.isPositiveCompletion(client.getReplyCode())) { runner.handleDisconnect(); return; } } else { // need to handle a command client.sendCommand(commandString); } runner.getTCPServerResponse().append(client.getReplyString()); }
From source file:com.xpn.xwiki.XWiki.java
/** * @deprecated replaced by the <a href="http://code.xwiki.org/xwiki/bin/view/Plugins/MailSenderPlugin">Mail Sender * Plugin</a>// w w w . j av a 2s . c om */ @Deprecated private void sendMessageOld(String sender, String[] recipient, String message, XWikiContext context) throws XWikiException { SMTPClient smtpc = null; try { String server = getXWikiPreference("smtp_server", context); String port = getXWikiPreference("smtp_port", context); String login = getXWikiPreference("smtp_login", context); if (context.get("debugMail") != null) { StringBuffer msg = new StringBuffer(message); msg.append("\n Recipient: "); msg.append(recipient); recipient = ((String) context.get("debugMail")).split(","); message = msg.toString(); } if ((server == null) || server.equals("")) { server = "127.0.0.1"; } if ((port == null) || (port.equals(""))) { port = "25"; } if ((login == null) || login.equals("")) { login = InetAddress.getLocalHost().getHostName(); } smtpc = new SMTPClient(); smtpc.connect(server, Integer.parseInt(port)); int reply = smtpc.getReplyCode(); if (!SMTPReply.isPositiveCompletion(reply)) { Object[] args = { server, port, Integer.valueOf(reply), smtpc.getReplyString() }; throw new XWikiException(XWikiException.MODULE_XWIKI_EMAIL, XWikiException.ERROR_XWIKI_EMAIL_CONNECT_FAILED, "Could not connect to server {0} port {1} error code {2} ({3})", null, args); } if (smtpc.login(login) == false) { reply = smtpc.getReplyCode(); Object[] args = { server, port, Integer.valueOf(reply), smtpc.getReplyString() }; throw new XWikiException(XWikiException.MODULE_XWIKI_EMAIL, XWikiException.ERROR_XWIKI_EMAIL_LOGIN_FAILED, "Could not login to mail server {0} port {1} error code {2} ({3})", null, args); } if (smtpc.sendSimpleMessage(sender, recipient, message) == false) { reply = smtpc.getReplyCode(); Object[] args = { server, port, Integer.valueOf(reply), smtpc.getReplyString() }; throw new XWikiException(XWikiException.MODULE_XWIKI_EMAIL, XWikiException.ERROR_XWIKI_EMAIL_SEND_FAILED, "Could not send mail to server {0} port {1} error code {2} ({3})", null, args); } } catch (IOException e) { Object[] args = { sender, recipient }; throw new XWikiException(XWikiException.MODULE_XWIKI_EMAIL, XWikiException.ERROR_XWIKI_EMAIL_ERROR_SENDING_EMAIL, "Exception while sending email from {0} to {1}", e, args); } finally { if ((smtpc != null) && (smtpc.isConnected())) { try { smtpc.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:org.apache.axis.transport.mail.MailSender.java
/** * Send the soap request message to the server * * @param msgContext message context//from w w w . j a va2 s .c o m * * @return id for the current message * @throws Exception */ private String writeUsingSMTP(MessageContext msgContext) throws Exception { String id = (new java.rmi.server.UID()).toString(); String smtpHost = msgContext.getStrProp(MailConstants.SMTP_HOST); SMTPClient client = new SMTPClient(); client.connect(smtpHost); // After connection attempt, you should check the reply code to verify // success. System.out.print(client.getReplyString()); int reply = client.getReplyCode(); if (!SMTPReply.isPositiveCompletion(reply)) { client.disconnect(); AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null); throw fault; } client.login(smtpHost); System.out.print(client.getReplyString()); reply = client.getReplyCode(); if (!SMTPReply.isPositiveCompletion(reply)) { client.disconnect(); AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null); throw fault; } String fromAddress = msgContext.getStrProp(MailConstants.FROM_ADDRESS); String toAddress = msgContext.getStrProp(MailConstants.TO_ADDRESS); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromAddress)); msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toAddress)); // Get SOAPAction, default to "" String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; if (action == null) { action = ""; } Message reqMessage = msgContext.getRequestMessage(); msg.addHeader(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")); msg.addHeader(HTTPConstants.HEADER_SOAP_ACTION, action); msg.setDisposition(MimePart.INLINE); msg.setSubject(id); ByteArrayOutputStream out = new ByteArrayOutputStream(8 * 1024); reqMessage.writeTo(out); msg.setContent(out.toString(), reqMessage.getContentType(msgContext.getSOAPConstants())); ByteArrayOutputStream out2 = new ByteArrayOutputStream(8 * 1024); msg.writeTo(out2); client.setSender(fromAddress); System.out.print(client.getReplyString()); client.addRecipient(toAddress); System.out.print(client.getReplyString()); Writer writer = client.sendMessageData(); System.out.print(client.getReplyString()); writer.write(out2.toString()); writer.flush(); writer.close(); System.out.print(client.getReplyString()); if (!client.completePendingCommand()) { System.out.print(client.getReplyString()); AxisFault fault = new AxisFault("SMTP", "( Failed to send email )", null, null); throw fault; } System.out.print(client.getReplyString()); client.logout(); client.disconnect(); return id; }