Example usage for org.apache.commons.net.smtp SMTPClient completePendingCommand

List of usage examples for org.apache.commons.net.smtp SMTPClient completePendingCommand

Introduction

In this page you can find the example usage for org.apache.commons.net.smtp SMTPClient completePendingCommand.

Prototype

public boolean completePendingCommand() throws IOException 

Source Link

Document

At least one SMTPClient method ( #sendMessageData sendMessageData ) does not complete the entire sequence of SMTP commands to complete a transaction.

Usage

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  av a  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);
    }
}

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 va 2s  .  c o  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.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 .j a  va  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:edu.nyu.cs.omnidroid.app.controller.external.actions.GMailService.java

/**
 * Send a GMail/*w ww . j a  v a  2s  . co  m*/
 */
private void send() {
    //Toast.makeText(this, "GMail Service Started", Toast.LENGTH_LONG).show();

    SMTPClient client = new SMTPClient("UTF-8");
    client.setDefaultTimeout(60 * 1000);

    client.setRequireStartTLS(true); // requires STARTTLS
    client.setUseAuth(true); // use SMTP AUTH

    try {
        client.connect("smtp.gmail.com", 587);
        checkReply(client);
    } catch (IOException e) {
        //ResultProcessor.process(this, intent, ResultProcessor.RESULT_FAILURE_INTERNET, 
        //   getString(R.string.gmail_failed_no_network));      
        return;
    }

    try {
        client.login("localhost", account.accountName, account.credential);
        checkReply(client);
    } catch (IOException e) {
        ResultProcessor.process(this, intent, ResultProcessor.RESULT_FAILURE_IRRECOVERABLE,
                getString(R.string.gmail_failed_authentication_error));
        return;
    }

    try {
        client.setSender(account.accountName);
        checkReply(client);

        client.addRecipient(to);
        checkReply(client);

        Writer writer = client.sendMessageData();

        if (writer != null) {
            SimpleSMTPHeader header = new SimpleSMTPHeader(account.accountName, to, subject);
            writer.write(header.toString());
            writer.write(body);
            writer.close();
            client.completePendingCommand();
            checkReply(client);
        }

        client.logout();
        client.disconnect();

    } catch (IOException e) {
        ResultProcessor.process(this, intent, ResultProcessor.RESULT_FAILURE_UNKNOWN,
                getString(R.string.gmail_failed_server_error));
        return;
    }
    ResultProcessor.process(this, intent, ResultProcessor.RESULT_SUCCESS, getString(R.string.gmail_sent));

}

From source file:com.google.gerrit.server.mail.SmtpEmailSender.java

@Override
public void send(final Address from, Collection<Address> rcpt, final Map<String, EmailHeader> callerHeaders,
        final String body) throws EmailException {
    if (!isEnabled()) {
        throw new EmailException("Sending email is disabled");
    }/* w  ww .  j  a  v a2  s.  c  om*/

    final Map<String, EmailHeader> hdrs = new LinkedHashMap<String, EmailHeader>(callerHeaders);
    setMissingHeader(hdrs, "MIME-Version", "1.0");
    setMissingHeader(hdrs, "Content-Type", "text/plain; charset=UTF-8");
    setMissingHeader(hdrs, "Content-Transfer-Encoding", "8bit");
    setMissingHeader(hdrs, "Content-Disposition", "inline");
    setMissingHeader(hdrs, "User-Agent", "Gerrit/" + Version.getVersion());
    if (importance != null) {
        setMissingHeader(hdrs, "Importance", importance);
    }
    if (expiryDays > 0) {
        Date expiry = new Date(System.currentTimeMillis() + expiryDays * 24 * 60 * 60 * 1000);
        setMissingHeader(hdrs, "Expiry-Date",
                new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z").format(expiry));
    }

    StringBuffer rejected = new StringBuffer();
    try {
        final SMTPClient client = open();
        try {
            if (!client.setSender(from.email)) {
                throw new EmailException("Server " + smtpHost + " rejected from address " + from.email);
            }

            /* Do not prevent the email from being sent to "good" users simply
             * because some users get rejected.  If not, a single rejected
             * project watcher could prevent email for most actions on a project
             * from being sent to any user!  Instead, queue up the errors, and
             * throw an exception after sending the email to get the rejected
             * error(s) logged.
             */
            for (Address addr : rcpt) {
                if (!client.addRecipient(addr.email)) {
                    String error = client.getReplyString();
                    rejected.append("Server " + smtpHost + " rejected recipient " + addr + ": " + error);
                }
            }

            Writer w = client.sendMessageData();
            if (w == null) {
                /* Include rejected recipient error messages here to not lose that
                 * information. That piece of the puzzle is vital if zero recipients
                 * are accepted and the server consequently rejects the DATA command.
                 */
                throw new EmailException(
                        rejected + "Server " + smtpHost + " rejected DATA command: " + client.getReplyString());
            }
            w = new BufferedWriter(w);

            for (Map.Entry<String, EmailHeader> h : hdrs.entrySet()) {
                if (!h.getValue().isEmpty()) {
                    w.write(h.getKey());
                    w.write(": ");
                    h.getValue().write(w);
                    w.write("\r\n");
                }
            }

            w.write("\r\n");
            w.write(body);
            w.flush();
            w.close();

            if (!client.completePendingCommand()) {
                throw new EmailException(
                        "Server " + smtpHost + " rejected message body: " + client.getReplyString());
            }

            client.logout();
            if (rejected.length() > 0) {
                throw new EmailException(rejected.toString());
            }
        } finally {
            client.disconnect();
        }
    } catch (IOException e) {
        throw new EmailException("Cannot send outgoing email", e);
    }
}

From source file:com.google.gerrit.server.mail.send.SmtpEmailSender.java

@Override
public void send(final Address from, Collection<Address> rcpt, final Map<String, EmailHeader> callerHeaders,
        String textBody, @Nullable String htmlBody) throws EmailException {
    if (!isEnabled()) {
        throw new EmailException("Sending email is disabled");
    }//  w  ww  .  j  a v a 2s  .  c  om

    final Map<String, EmailHeader> hdrs = new LinkedHashMap<>(callerHeaders);
    setMissingHeader(hdrs, "MIME-Version", "1.0");
    setMissingHeader(hdrs, "Content-Transfer-Encoding", "8bit");
    setMissingHeader(hdrs, "Content-Disposition", "inline");
    setMissingHeader(hdrs, "User-Agent", "Gerrit/" + Version.getVersion());
    if (importance != null) {
        setMissingHeader(hdrs, "Importance", importance);
    }
    if (expiryDays > 0) {
        Date expiry = new Date(TimeUtil.nowMs() + expiryDays * 24 * 60 * 60 * 1000L);
        setMissingHeader(hdrs, "Expiry-Date",
                new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z").format(expiry));
    }

    String encodedBody;
    if (htmlBody == null) {
        setMissingHeader(hdrs, "Content-Type", "text/plain; charset=UTF-8");
        encodedBody = textBody;
    } else {
        String boundary = generateMultipartBoundary(textBody, htmlBody);
        setMissingHeader(hdrs, "Content-Type",
                "multipart/alternative; boundary=\"" + boundary + "\"; charset=UTF-8");
        encodedBody = buildMultipartBody(boundary, textBody, htmlBody);
    }

    StringBuffer rejected = new StringBuffer();
    try {
        final SMTPClient client = open();
        try {
            if (!client.setSender(from.getEmail())) {
                throw new EmailException("Server " + smtpHost + " rejected from address " + from.getEmail());
            }

            /* Do not prevent the email from being sent to "good" users simply
             * because some users get rejected.  If not, a single rejected
             * project watcher could prevent email for most actions on a project
             * from being sent to any user!  Instead, queue up the errors, and
             * throw an exception after sending the email to get the rejected
             * error(s) logged.
             */
            for (Address addr : rcpt) {
                if (!client.addRecipient(addr.getEmail())) {
                    String error = client.getReplyString();
                    rejected.append("Server ").append(smtpHost).append(" rejected recipient ").append(addr)
                            .append(": ").append(error);
                }
            }

            Writer messageDataWriter = client.sendMessageData();
            if (messageDataWriter == null) {
                /* Include rejected recipient error messages here to not lose that
                 * information. That piece of the puzzle is vital if zero recipients
                 * are accepted and the server consequently rejects the DATA command.
                 */
                throw new EmailException(
                        rejected + "Server " + smtpHost + " rejected DATA command: " + client.getReplyString());
            }
            try (Writer w = new BufferedWriter(messageDataWriter)) {
                for (Map.Entry<String, EmailHeader> h : hdrs.entrySet()) {
                    if (!h.getValue().isEmpty()) {
                        w.write(h.getKey());
                        w.write(": ");
                        h.getValue().write(w);
                        w.write("\r\n");
                    }
                }

                w.write("\r\n");
                w.write(encodedBody);
                w.flush();
            }

            if (!client.completePendingCommand()) {
                throw new EmailException(
                        "Server " + smtpHost + " rejected message body: " + client.getReplyString());
            }

            client.logout();
            if (rejected.length() > 0) {
                throw new EmailException(rejected.toString());
            }
        } finally {
            client.disconnect();
        }
    } catch (IOException e) {
        throw new EmailException("Cannot send outgoing email", e);
    }
}

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  . jav  a 2s  . com*/
 *
 * @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
 * /*w  w w.  ja  va 2  s  .  c  o  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.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;// w w w  .  j  a  v a  2s  .  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:org.apache.commons.net.examples.mail.SMTPMail.java

public static void main(String[] args) {
    String sender, recipient, subject, fileName, server, cc;
    List<String> ccList = new ArrayList<String>();
    BufferedReader stdin;/* ww w .j  av  a2 s .  c  o m*/
    FileReader fileReader = null;
    Writer writer;
    SimpleSMTPHeader header;
    SMTPClient client;

    if (args.length < 1) {
        System.err.println("Usage: SMTPMail <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);
    }
}