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

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

Introduction

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

Prototype

public boolean setSender(String address) throws IOException 

Source Link

Document

Set the sender of a message using the SMTP MAIL command, specifying the sender's email address.

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;/* ww  w . java  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;//  ww  w  .ja v  a2  s  .  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.Module.RegisterModule.java

public static boolean checkEmail(String email) {
    if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
        return false;
    }/*w w w .j  av a  2  s.c  o  m*/

    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.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 .ja va  2  s .com*/
        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:me.normanmaurer.camel.smtp.SMTPTest.java

@SuppressWarnings("unchecked")
@Test/*from  w  ww.jav  a2s .c  o  m*/
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", 2525);
    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:com.google.code.camel.smtp.SMTPTest.java

@SuppressWarnings("unchecked")
@Test/*from  w ww.j  av  a  2 s .  c om*/
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", 2525);
    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();
    System.out.println(header.toString());
    if (header.getName().equals("Subject")) {
        break;
    }
    }
    assertNotNull(header);
    assertEquals("Subject", header.getName());
    assertEquals(header.getValue(), "test");
    */
    resultEndpoint.assertIsSatisfied();
}

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");
    }//from   ww  w . j av  a  2 s .co  m

    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");
    }/*from w w  w.  j av  a 2  s .  c  o m*/

    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:edu.nyu.cs.omnidroid.app.controller.external.actions.GMailService.java

/**
 * Send a GMail/*from  w w w.j a  v  a  2s  .c o  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:emailchecker.CheckEmailObj.java

public boolean checkEmail(String email) {
    if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
        System.err.println("Format error");
        return false;
    }/*  ww w . j  ava  2  s.c o 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;
}