Sample code for 30+ languages & platforms
Android™

Close a Persistent SMTP Connection

See more SMTP Examples

Demonstrates the Chilkat MailMan.CloseSmtpConnection method, which explicitly closes the current SMTP connection. Before closing the socket, Chilkat sends the SMTP QUIT command so the server can end the session cleanly. This example opens a connection and then closes it.

Background: This is the companion to OpenSmtpConnection and completes the "open once, send many, close once" batch pattern. Sending QUIT before dropping the socket is proper SMTP etiquette: it tells the server you are finished so it can release resources gracefully rather than treating the disconnect as an abrupt drop.

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    //  Demonstrates the MailMan.CloseSmtpConnection method, which explicitly closes the current
    //  SMTP connection.  Before closing the socket, Chilkat sends the SMTP QUIT command.

    CkMailMan mailman = new CkMailMan();

    //  Configure the SMTP server connection.
    mailman.put_SmtpHost("smtp.example.com");
    mailman.put_SmtpPort(465);
    mailman.put_SmtpSsl(true);
    mailman.put_SmtpUsername("user@example.com");
    mailman.put_SmtpPassword("myPassword");

    //  Open a connection (which would be reused for multiple sends).

    success = mailman.OpenSmtpConnection();
    if (success == false) {
        Log.i(TAG, mailman.lastErrorText());
        return;
        }

    //  ... send emails here ...

    //  Explicitly close the SMTP connection (sends QUIT first).
    success = mailman.CloseSmtpConnection();
    if (success == false) {
        Log.i(TAG, mailman.lastErrorText());
        return;
        }

    Log.i(TAG, "SMTP connection closed.");

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}