Sample code for 30+ languages & platforms
Android™ Requires Chilkat v11.0.0+

Sign and encrypt an email with S/MIME

See more Email Object Examples

Use the sender’s signing PFX and the recipient’s public RSA certificate with with-attachments.eml, which has one recipient. Supply your own signing-key password from a credential store. Render to bytes to apply both S/MIME operations without connecting to SMTP.

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;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    CkEmail email = new CkEmail();
    success = email.LoadEml("with-attachments.eml");
    if (success != true) {
        Log.i(TAG, email.lastErrorText());
        return;
        }

    CkCert signer = new CkCert();
    success = signer.LoadPfxFile("signer.pfx","SIGNER_PASSWORD");
    if (success != true) {
        Log.i(TAG, signer.lastErrorText());
        return;
        }

    CkCert recipient = new CkCert();
    success = recipient.LoadFromFile("recipient.cer");
    if (success != true) {
        Log.i(TAG, recipient.lastErrorText());
        return;
        }

    success = email.SetSigningCert(signer);
    if (success != true) {
        Log.i(TAG, email.lastErrorText());
        return;
        }

    success = email.SetEncryptCert(recipient);
    if (success != true) {
        Log.i(TAG, email.lastErrorText());
        return;
        }

    email.put_SigningHashAlg("sha256");
    email.put_Pkcs7CryptAlg("aes");
    email.put_Pkcs7KeyLength(256);
    email.put_OaepPadding(true);
    email.put_OaepHash("sha256");
    email.put_OaepMgfHash("sha256");
    email.put_SendSigned(true);
    email.put_SendEncrypted(true);
    CkMailMan mail = new CkMailMan();
    CkBinData rendered = new CkBinData();
    success = mail.RenderToMimeBd(email,rendered);
    if (success != true) {
        Log.i(TAG, mail.lastErrorText());
        return;
        }

    success = rendered.WriteFile("signed-encrypted.eml");
    if (success != true) {
        Log.i(TAG, "Failed: rendered.WriteFile.");
        return;
        }

    Log.i(TAG, "Saved signed-encrypted.eml.");

  }

  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."
  }
}