List of usage examples for org.apache.commons.net.smtp SMTPClient SMTPClient
public SMTPClient()
From source file:adams.core.net.ApacheSendEmail.java
/** * Initializes the SMTP session./* w ww . ja v a 2s . c o m*/ * * @param server the SMTP server * @param port the SMTP port * @param useTLS whether to use TLS * @param useSSL whether to use SSL * @param timeout the timeout * @param requiresAuth whether authentication is required * @param user the SMTP user * @param pw the SMTP password * @return the session * @throws Exception if initialization fails */ @Override public void initializeSmtpSession(String server, int port, boolean useTLS, boolean useSSL, int timeout, boolean requiresAuth, String user, BasePassword pw) throws Exception { m_Server = server; m_Port = port; m_UseTLS = useTLS; m_UseSSL = useSSL; m_Timeout = timeout; m_RequiresAuth = requiresAuth; m_User = user; m_Password = pw; // TODO SSL? if (m_UseTLS) { if (m_RequiresAuth) m_Client = new AuthenticatingSMTPClient(); else m_Client = new SMTPSClient(); } else { m_Client = new SMTPClient(); } m_Client.setConnectTimeout(m_Timeout); if (isLoggingEnabled()) m_Client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); }
From source file:me.schiz.jmeter.protocol.smtp.sampler.SMTPSampler.java
private SampleResult sampleConnect(SampleResult sr) { SMTPClient client;/* www . ja v a 2 s.c o m*/ if (getUseSSL()) { client = new SMTPSClient(true); } else if (getUseSTARTTLS()) { client = new SMTPSClient(false); } else { client = new SMTPClient(); } try { String request = "CONNECT \n"; request += "Host : " + getHostname() + ":" + getPort() + "\n"; request += "Default Timeout : " + getDefaultTimeout() + "\n"; request += "Connect Timeout : " + getConnectionTimeout() + "\n"; request += "So Timeout : " + getSoTimeout() + "\n"; request += "Client : " + getClient() + "\n"; if (getUseSSL()) request += "SSL : true\n"; else request += "SSL : false\n"; if (getUseSTARTTLS()) request += "STARTTLS : true\n"; else request += "STARTTLS : false\n"; sr.setRequestHeaders(request); sr.sampleStart(); client.setDefaultTimeout(getDefaultTimeout()); client.setConnectTimeout(getConnectionTimeout()); client.connect(getHostname(), getPort()); if (client.isConnected()) { SessionStorage.proto_type protoType = SessionStorage.proto_type.PLAIN; if (getUseSSL() && !getUseSTARTTLS()) protoType = SessionStorage.proto_type.SSL; if (!getUseSSL() && getUseSTARTTLS()) protoType = SessionStorage.proto_type.STARTTLS; SessionStorage.getInstance().putClient(getSOClient(), client, protoType); client.setSoTimeout(getSoTimeout()); client.setTcpNoDelay(getTcpNoDelay()); sr.setResponseCode(String.valueOf(client.getReplyCode())); sr.setResponseData(client.getReplyString().getBytes()); setSuccessfulByResponseCode(sr, client.getReplyCode()); } } catch (SocketException se) { sr.setResponseMessage(se.toString()); sr.setSuccessful(false); sr.setResponseCode(se.getClass().getName()); log.error("client `" + client + "` ", se); } catch (IOException ioe) { sr.setResponseMessage(ioe.toString()); sr.setSuccessful(false); sr.setResponseCode(ioe.getClass().getName()); log.error("client `" + client + "` ", ioe); } sr.sampleEnd(); return sr; }
From source file:autohit.call.modules.SimpleSmtpModule.java
/** * Start method. It will open a connection to an SMTP server/relay. If a * session is already started, it will report an error. If it cannot make * the connection, it will cause a fault. * //from w ww. j a v a 2 s . c o m * @param addr * the domain name address. Do not include protocol or port. * @param post * this should be a parsable integer. If it is null, the default * will be used. * @throws CallException */ private void start(String addr, String port) throws CallException { SMTPClient candidate = null; // Already started? if (client != null) { this.error("Session already started. Ignoring new start()."); return; } // Passed a port number? int portNum = 0; if (port != null) { try { portNum = Integer.parseInt(port); } catch (Exception e) { this.fault("Malformed 'port' number. It must be a parsable integer. text=" + port); } } // Try and construct it try { candidate = new SMTPClient(); if (port == null) { candidate.connect(addr); } else { candidate.connect(addr, portNum); } } catch (Exception ex) { if (client.isConnected()) { try { client.disconnect(); } catch (IOException f) { // do nothing } } this.fault("Could not connect to host. message=" + ex.getMessage()); } // NO CODE AFTER THIS! this.log("Connection started."); client = candidate; }
From source file:autohit.call.modules.TolerantSmtpModule.java
/** * Start method. It will open a connection to an SMTP server/relay. If a * session is already started, it will report an error. If it cannot make * the connection, it will cause a fault. * /* w ww. ja v a 2s .c o m*/ * @param addr * the domain name address. Do not include protocol or port. * @param post * this should be a parsable integer. If it is null, the default * will be used. * @throws CallException */ private void start(String addr, String port) throws CallException { SMTPClient candidate = null; // Already started? if (client != null) { this.error("Session already started. Ignoring new start()."); return; } // Passed a port number? int portNum = 0; if (port != null) { try { portNum = Integer.parseInt(port); } catch (Exception e) { this.fault("Malformed 'port' number. It must be a parsable integer. text=" + port); } } // Try and construct it try { candidate = new SMTPClient(); if (port == null) { candidate.connect(addr); } else { candidate.connect(addr, portNum); } } catch (Exception ex) { this.error("Could not connect to host. message=" + ex.getMessage()); return; } // NO CODE AFTER THIS! this.log("Connection started."); loggedIn = false; client = candidate; }
From source file:ProtocolRunner.java
public static SocketClient getTCPClientInstance(int clientType) { switch(clientType) { case 0: { // is chargen if(charGenTCPClient == null) { charGenTCPClient = new CharGenTCPClient(); }//from w ww . j a va2 s . c o m return charGenTCPClient; } case 1: { // is daytime if(daytimeTCPClient == null) { daytimeTCPClient = new DaytimeTCPClient(); } return daytimeTCPClient; } case 2: { // is echo if(echoTCPClient == null) { echoTCPClient = new EchoTCPClient(); } return echoTCPClient; } case 3: { // is finger if(fingerClient == null) { fingerClient = new FingerClient(); } return fingerClient; } case 4: { // is ftp if(ftpClient == null) { ftpClient = new FTPClient(); } return ftpClient; } case 5: { // is nntp if(nntpClient == null) { nntpClient = new NNTPClient(); } return nntpClient; } case 6: { // is pop3 if(pop3Client == null) { pop3Client = new POP3Client(); } return pop3Client; } case 7: { // is smtp if(smtpClient == null) { smtpClient = new SMTPClient(); } return smtpClient; } case 8: { // is time if(timeTCPClient == null) { timeTCPClient = new TimeTCPClient(); } return timeTCPClient; } case 9: { // is whois if(whoisClient == null) { whoisClient = new WhoisClient(); } return whoisClient; } } return null; }
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>/*from www. j a v a2s . c o m*/ */ @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 v a2 s.c om*/ * * @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; }
From source file:org.apache.axis.transport.mail.MailWorker.java
/** * Send the soap request message to the server * //from w w w. j av a 2 s. co m * @param msgContext * @param smtpHost * @param sendFrom * @param replyTo * @param output * @throws Exception */ private void writeUsingSMTP(MessageContext msgContext, String smtpHost, String sendFrom, String replyTo, String subject, Message output) throws Exception { 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; } MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(sendFrom)); msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(replyTo)); msg.setDisposition(MimePart.INLINE); msg.setSubject(subject); ByteArrayOutputStream out = new ByteArrayOutputStream(8 * 1024); output.writeTo(out); msg.setContent(out.toString(), output.getContentType(msgContext.getSOAPConstants())); ByteArrayOutputStream out2 = new ByteArrayOutputStream(8 * 1024); msg.writeTo(out2); client.setSender(sendFrom); System.out.print(client.getReplyString()); client.addRecipient(replyTo); 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(); }
From source file:org.apache.camel.component.james.smtp.SMTPTest.java
/** * Test send matching message./*from ww w .j a va 2s . c o m*/ * * @throws Exception * the exception */ @SuppressWarnings("unchecked") @Test public void testSendMatchingMessage() throws Exception { String sender = "sender@localhost"; String rcpt = "rcpt@localhost"; String body = "Subject: test\r\n\r\nTestmail"; SMTPClient client = new SMTPClient(); client.connect("localhost", port); client.helo("localhost"); client.setSender(sender); client.addRecipient(rcpt); client.sendShortMessageData(body); client.quit(); client.disconnect(); resultEndpoint.expectedMessageCount(1); resultEndpoint.expectedBodyReceived().body(InputStream.class); Exchange ex = resultEndpoint.getReceivedExchanges().get(0); Map<String, Object> headers = ex.getIn().getHeaders(); assertEquals(sender, headers.get(MailEnvelopeMessage.SMTP_SENDER_ADRRESS)); assertEquals(rcpt, headers.get(MailEnvelopeMessage.SMTP_RCPT_ADRRESS_LIST)); // check type converter MimeMessage message = ex.getIn().getBody(MimeMessage.class); Enumeration<Header> mHeaders = message.getAllHeaders(); Header header = null; while (mHeaders.hasMoreElements()) { header = mHeaders.nextElement(); if (header.getName().equals("Subject")) { break; } } assertNotNull(header); assertEquals("Subject", header.getName()); assertEquals(header.getValue(), "test"); resultEndpoint.assertIsSatisfied(); }
From source file:org.apache.common.net.examples.mail.SMTPMail.java
public final static void main(String[] args) { String sender, recipient, subject, filename, server, cc; List<String> ccList = new ArrayList<String>(); BufferedReader stdin;/*from w w w .j ava 2 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); } }