Example usage for org.apache.commons.net.smtp SimpleSMTPHeader addCC

List of usage examples for org.apache.commons.net.smtp SimpleSMTPHeader addCC

Introduction

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

Prototype

public void addCC(String address) 

Source Link

Document

Add an email address to the CC (carbon copy or courtesy copy) list.

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 w w. j a  v  a2s .  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  ww. jav a 2  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:ca.rmen.android.networkmonitor.app.email.Emailer.java

/**
 * Sends an e-mail in UTF-8 encoding.//  w  w  w  .j  ava 2 s  .  c  om
 *
 * @param protocol    this has been tested with "TLS", "SSL", and null.
 * @param attachments optional attachments to include in the mail.
 * @param debug       if true, details about the smtp commands will be logged to stdout.
 */
static void sendEmail(String protocol, String server, int port, String user, String password, String from,
        String[] recipients, String subject, String body, Set<File> attachments, boolean debug)
        throws Exception {

    // Set up the mail connectivity
    final AuthenticatingSMTPClient client;
    if (protocol == null)
        client = new AuthenticatingSMTPClient();
    else
        client = new AuthenticatingSMTPClient(protocol);

    if (debug)
        client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    client.setDefaultTimeout(SMTP_TIMEOUT_MS);
    client.setCharset(Charset.forName(ENCODING));
    client.connect(server, port);
    checkReply(client);
    client.helo("[" + client.getLocalAddress().getHostAddress() + "]");
    checkReply(client);
    if ("TLS".equals(protocol)) {
        if (!client.execTLS()) {
            checkReply(client);
            throw new RuntimeException("Could not start tls");
        }
    }
    client.auth(AuthenticatingSMTPClient.AUTH_METHOD.LOGIN, user, password);
    checkReply(client);

    // Set up the mail participants
    client.setSender(from);
    checkReply(client);
    for (String recipient : recipients) {
        client.addRecipient(recipient);
        checkReply(client);
    }

    // Set up the mail content
    Writer writer = client.sendMessageData();
    SimpleSMTPHeader header = new SimpleSMTPHeader(from, recipients[0], subject);
    for (int i = 1; i < recipients.length; i++)
        header.addCC(recipients[i]);

    // Just plain text mail: no attachments
    if (attachments == null || attachments.isEmpty()) {
        header.addHeaderField("Content-Type", "text/plain; charset=" + ENCODING);
        writer.write(header.toString());
        writer.write(body);
    }
    // Mail with attachments
    else {
        String boundary = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 28);
        header.addHeaderField("Content-Type", "multipart/mixed; boundary=" + boundary);
        writer.write(header.toString());

        // Write the main text message
        writer.write("--" + boundary + "\n");
        writer.write("Content-Type: text/plain; charset=" + ENCODING + "\n\n");
        writer.write(body);
        writer.write("\n");

        // Write the attachments
        appendAttachments(writer, boundary, attachments);
        writer.write("--" + boundary + "--\n\n");
    }

    writer.close();
    if (!client.completePendingCommand()) {
        throw new RuntimeException("Could not send mail");
    }
    client.logout();
    client.disconnect();
}

From source file:adams.core.net.ApacheSendEmail.java

/**
 * Sends an email.//from  w ww  .j av a  2s.  c o  m
 *
 * @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: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   ww  w.j a v  a 2 s . c om*/
    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;/*from   w  ww .ja v a  2s  .  com*/
    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);
    }
}