Example usage for org.apache.commons.net.smtp AuthenticatingSMTPClient AuthenticatingSMTPClient

List of usage examples for org.apache.commons.net.smtp AuthenticatingSMTPClient AuthenticatingSMTPClient

Introduction

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

Prototype

public AuthenticatingSMTPClient() throws NoSuchAlgorithmException 

Source Link

Document

The default AuthenticatingSMTPClient constructor.

Usage

From source file:ca.rmen.android.networkmonitor.app.email.Emailer.java

/**
 * Sends an e-mail in UTF-8 encoding.//ww  w  .j a v a  2 s. c o  m
 *
 * @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:com.ironiacorp.email.CommonsNetEmailDispatcher.java

@Override
public void sendEmails(Email... emails) {
    AuthenticatingSMTPClient client = null;
    boolean result = false;
    int port = connectionType.port;
    if (serverPort != 0) {
        port = serverPort;//  w w  w  .ja  v a2 s.c  om
    }

    try {
        client = new AuthenticatingSMTPClient();

        client.connect(serverName, port);
        if (connectionType == EmailServerConnectionType.SSL
                || connectionType == EmailServerConnectionType.TLS) {
            result = client.execTLS();
            if (result == false) {
                throw new IllegalArgumentException("Cannot start secure connection");
            }
        }

        if (authenticationRequired) {
            result = client.auth(AUTH_METHOD.PLAIN, username, password);
            if (result == false) {
                throw new IllegalArgumentException("Incorrect username or password");
            }
        }

        // After connection attempt, you should check the reply code to verify success.
        int reply = client.getReplyCode();
        if (!SMTPReply.isPositiveCompletion(reply)) {
            client.disconnect();
        }

        for (Email email : emails) {
            SimpleSMTPHeader header;
            Iterator<Recipient> i = email.getRecipients().iterator();
            Writer writer = client.sendMessageData();
            String to = null;

            while (i.hasNext()) {
                Recipient recipient = i.next();
                if (to == null && email.getVisibility(recipient) == Visibility.TO) {
                    to = recipient.getEmail();
                } else {
                    client.addRecipient(recipient.getEmail());
                }
            }

            header = new SimpleSMTPHeader(email.getSender().getEmail(), null, email.getSubject());

            writer.write(header.toString());
            result = client.completePendingCommand();
            if (result == false) {
                throw new IllegalArgumentException("Could not send the email");
            }
            client.reset();
        }
    } catch (Exception e) {
        throw new UnsupportedOperationException("Could not send the email", e);
    } finally {
        if (client != null && client.isConnected()) {
            try {
                client.disconnect();
            } catch (IOException e) {
            }
        }

    }
}

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

/**
 * Initializes the SMTP session./*from  ww w.  j  a  v  a  2 s  .com*/
 *
 * @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:net.metanotion.emailqueue.SmtpSender.java

@Override
public Connection getConnection() {
    AuthenticatingSMTPClient client = null;
    try {//from w w  w  .  ja v a2 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:org.apache.james.mailets.utils.SMTPMessageSender.java

public static SMTPMessageSender authentication(String ip, int port, String senderDomain, String username,
        String password)//from w  ww  .j  a  v  a  2  s. c  o  m
        throws NoSuchAlgorithmException, IOException, InvalidKeySpecException, InvalidKeyException {
    AuthenticatingSMTPClient smtpClient = new AuthenticatingSMTPClient();
    smtpClient.connect(ip, port);
    smtpClient.auth(AuthenticatingSMTPClient.AUTH_METHOD.PLAIN, username, password);
    return new SMTPMessageSender(smtpClient, senderDomain);
}

From source file:org.apache.james.utils.SMTPMessageSender.java

public static SMTPMessageSender noAuthentication(String ip, int port, String senderDomain) throws IOException {
    AuthenticatingSMTPClient smtpClient = new AuthenticatingSMTPClient();
    smtpClient.connect(ip, port);//from www.ja v  a2  s .c  o m
    return new SMTPMessageSender(smtpClient, senderDomain);
}

From source file:org.apache.james.utils.SMTPMessageSender.java

public static SMTPMessageSender authentication(String ip, int port, String senderDomain, String username,
        String password)/*from w ww. j av  a 2 s .  c  o m*/
        throws NoSuchAlgorithmException, IOException, InvalidKeySpecException, InvalidKeyException {
    AuthenticatingSMTPClient smtpClient = new AuthenticatingSMTPClient();
    smtpClient.connect(ip, port);
    if (smtpClient.auth(AuthenticatingSMTPClient.AUTH_METHOD.PLAIN, username, password) == false) {
        throw new RuntimeException("auth failed");
    }
    return new SMTPMessageSender(smtpClient, senderDomain);
}

From source file:org.apache.james.utils.SMTPMessageSender.java

public SMTPMessageSender(String senderDomain) {
    this(new AuthenticatingSMTPClient(), senderDomain);
}